There are numerous tips in Ruby but I seem to keep forgetting them and having to search for them every time. So high time I started documenting them out.

This one I learnt from 10 Tips & Tricks from Drifting Ruby. I’m only going to keep to Ruby specific ones.

Underscore method

How come I didn’t know about this one?

Many times in irb, we type in commands to see the result but then realize that we would like to store it in a variable. So, we end up rerunning the same command with the variable assignment before that.

The underscore method just sets the variable to the last executed command!

irb> 1 + 2 + 3
=> 6
irb> sum = _
=> 6
irb> sum
=> 6

Class and Instance methods

Many times I need to open a console with the models loaded. To achieve this, in irb we can load bundler and the environment before loading the models.

To see the the class and instance methods against a Ruby class, we can pass false as the first parameter to be able to see the methods directly.

irb> require 'bundler'
irb> Bbundler.require
irb> Dotenv.load
irb> require_relative './models.rb'
irb> User.methods(false)
=> [:logout]
irb> User.instance_methods(false)
=> [:login]