IRB – Ruby's playground
Every computer with Ruby already ships with IRB (“Interactive RuBy”). You start it by typing irb into a terminal – then you feed Ruby one line at a time, and just like this notebook IRB shows each line's value with =>:
$ irb
irb(main):001:0> 1 + 1
=> 2
irb(main):002:0> "Chunky " + "Bacon!"
=> "Chunky Bacon!"Rubyists keep IRB open all the time: for experiments, quick math, and checking what a method returns. Here is a real IRB session for you – type into the terminal below and press Enter:
show_irbThree tricks every IRB pro knows – try them above:
_(underscore) is always the last answer: first6 * 7, then_ + 1.- IRB understands multi-line input: type
def double(x)– the prompt gets a*and waits until you deliverx * 2andend. exitquits IRB (on your machine … here the fox refuses to leave).
On your machine IRB can do even more. A few commands to try:
helplists all commands.ls "bacon"lists what an object can do: its methods, sorted by class.show_doc String#centershows a method's documentation – how to read documentation is the topic of the next lesson.show_sourceshows the source code of a method written in Ruby.- While you type, IRB suggests matching methods; Tab accepts a suggestion.
Look it up: The IRB guide
Task: Use the cell below like an IRB line: triple every number in the array
[4, 8, 15] using map – the value should be [12, 24, 45]. (Experiment in the terminal above first!)# [4, 8, 15].map { |x| ... }