IRB For The Win

What is the IRB?

At some point in your Ruby development career, someone will ask you, "Startup IRB so we can test this code". What do you do now? You can't search Google for IRB while the other developer is staring at your computer screen. Lucky for you, you read this blog post and know IRB stands for interactive ruby.

This powerful command-line program allows you to execute lines of Ruby code from a terminal. You can essentially create ruby programs on the fly, line by line. Follow the steps below to try it out.

  1. Open your Terminal of choice.
  2. Type `irb` in your shell and press Enter.
  3. Type `name = 'jane'` and press Enter.
  4. Type `3.times { puts name }` and press Enter.

Your output should look like this:

  ➜  ~ irb
  irb(main):001:0> name = 'Jane'
  => "Jane"
  irb(main):002:0> 3.times { puts name }
  => 3

Nothing fancy here. We started up IRB, created the variable name and printed the value of name 3 times. Each time we press Enter, IRB evaluates the Ruby we typed. The `=>` printed below each statement points to the value that was returned. If this doesn't make sense to you, you can read about Expressions for clarification. It's also possible to define methods and classes using IRB. Nothing is saved to permanent storage so you probably won't want to create anything important.

Why Should I Care?

Learning the basic syntax of Ruby is pretty easy but it's only the beginning of your journey as a Ruby developer. The Ruby Core Library contains many classes and methods that will simplify and improve our code. It's impossible to know the entire core library by heart though. This means you will refer to Ruby Docs often for clarification (at least you should be doing this). Most descriptions and usage examples on here are clear and easy to understand but when they're not we have the IRB. Use this program to try out examples and test your understanding of how a class or method works. You could write a small program or try them out in your existing code but using the IRB eliminates any distractions. You can focus on the new thing you're trying to learn rather than getting confused by outside factors. 

Next Time You're Confused

Next time when you find yourself confused by how a method or class works, try taking a step back before visiting StackOverflow. Read the documentation for that class or method. Look at the examples, start up IRB and try it yourself. You might be surprised to find out your assumptions are wrong. That's OK. It's better for us to take the time to understand how a method or class works before we use it in our program. This approach can lower the possibility of introducing bugs due to our lack of knowledge.