irb, or Interactive Ruby Shell, is a REPL that ships with Ruby. It allows you to experiment with the Ruby programming language in realtime. You start irb from the command line, enter some Ruby code, and irb prints out the results for you.
You'd have to install Ruby to use irb, but installing Ruby is beyond the scope of this article.
To start the interactive shell run the command irb
and you will see the following output
2.2.0 :001 >
You can make the interpreter behave a certain way by passing it command line switches. I won't cover all the switches here, but we'll look at some commonly used ones.
irb --simple-prompt
Make irb
output much easier to read
➜ ~/Desktop/ruby_code irb
2.2.0 :001 > { :key => "foo" }
=> {:key=>"hey"}
2.2.0 :002 >
➜ ~/Desktop/ruby_code irb --simple-promt
>> { :key => "foo" }
=> {:key=>"hey"}
>>
irb -c foo.rb
Check the syntax of one or more files without executing the code. Usually used in conjuction with the -w
flag.
➜ ~/Desktop/ruby_code ruby -c foo.rb
Syntax OK
➜ ~/Desktop/ruby_code ruby -c foo.rb
foo.rb:1: syntax error, unexpected =>, expecting end-of-input
:key => "foo" }
^
irb -w foo.rb
In warning mode the interpreter will be more chatty than usual. Even though the interpreter might not report back on any syntactical errors, it will still issue warnings about code that looks weird.
Consider the following Person
class
class Person
attr_accessor :first_name, :last_name
def initialize(first_name, last_name)
@first_name = first_name
@last_name = last_name
end
end
john = Person.new('John', 'Doe')
Now lets run the interpreter in warning mode and see what happens
irb -w foo.rb
➜ ~/Desktop/ruby_code ruby -w foo.rb
foo.rb:8: warning: assigned but unused variable - john
The warning tells us that even though the syntax in foo.rb
is OK, you are doing nothing with the variable john