Skip to content

Instantly share code, notes, and snippets.

@bjorntheart
Last active August 29, 2015 14:16
Show Gist options
  • Save bjorntheart/1e450cc72c292f2f5a37 to your computer and use it in GitHub Desktop.
Save bjorntheart/1e450cc72c292f2f5a37 to your computer and use it in GitHub Desktop.
Who is this irb REPL guy?

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.

Using irb

To start the interactive shell run the command irb and you will see the following output

2.2.0 :001 >

Command Line Switches

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.

--simple-prompt

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"}
>> 

Check Syntax (-c)

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" }
        ^

Turn on Warnings (-w)

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment