Amazing Rails Console / IRB Trick

When you’re playing around in IRB or Rails Console, you might come up with an output that you wanted to save as a variable, but didn’t (you’re playing around after all!). Now you have to retype your long statement all over again and this time save it to a variable.


So let’s get into IRB (just type irb in your terminal), type your name as a string, and press enter. Oh wait, but you wanted to save your name to a variable called name! Your choice is to just type name = “YOUR NAME” or click the up arrow to get the last input, then go to the beginning of the line (Control + A) and assign the name that way. Both are tedious and not fun. Feel free to do this just to feel the pain.

1.9.2p290 :006 > "NatashaTheRobot"
 => "NatashaTheRobot" 
1.9.2p290 :007 > name = "NatashaTheRobot"
 => "NatashaTheRobot" 
1.9.2p290 :008 > name
 => "NatashaTheRobot" 

Now go to a new line in IRB, and type a friends name and click enter. But wait, you wanted to save it as a the variable friends_name. Here is the fun way to do this:

1.9.2p290 :003 > "Jenny"
 => "Jenny" 
1.9.2p290 :004 > friends_name = _
 => "Jenny" 
1.9.2p290 :005 > friends_name
 => "Jenny" 

Boom! Now your friends name is saved! This “x = _” trick also works in the Rails Console.

Do you use any cool IRB / Rails Console tricks? Please share in the comments!

Enjoy the article? Join over 14,500+ Swift developers and enthusiasts who get my weekly updates.

  • Hey, never know about this trick in irb, thanks for sharing 🙂