Ruby 1.9 – Tap my Object

posted by Arkham on October 28th, 2011

Let’ say you need to debug this piece of code:

very_cool_method(egg, sausage)

What would you do? I guess something along the lines of:

spam = very_cool_method(egg, sausage)
p spam

Well, Ruby 1.9 let you do something cooler instead:

very_cool_method(egg, sausage).tap{ |s| p s }

The cool thing about tap is that you can use it to eavesdrop method chains:

very_cool_method(egg, sausage).tap{ |s| p s }.now_make_sandwich_from(bacon)

Hooray! :)

Tags: , , , ,

Rails: how to show SQL logs in console

posted by Arkham on September 2nd, 2011

Simply type in rails console:

ActiveRecord::Base.logger =

Tags: , , ,

Ruby: disable documentation when installing gems

posted by Arkham on July 29th, 2011

If you want to install gems quickly without waiting for ri and rdoc documentation files, run this command:

echo "gem: --no-ri --no-rdoc" >> ~/.gemrc

Your new gems won’t include documentation at all. Hooray!

Tags: ,

Ruby, difference from instance_eval and class_eval

posted by Arkham on July 5th, 2011

String.instance_eval { def foo; p "bar"; end } = "bar"
String.class_eval { def foo; p "bar"; end }
"sausage".foo = "bar"

So, using instance_eval adds a class method.
On the other hand, using class_eval adds a instance method.


class_eval is a method of the Module class, meaning that the receiver will be a module or a class. The block you pass to class_eval is evaluated in the context of that class. Defining a method with the standard def keyword within a class defines an instance method, and that’s exactly what happens here.

instance_eval, on the other hand, is a method of the Object class, meaning that the receiver will be an object. The block you pass to instance_eval is evaluated in the context of that object. That means that String.instance_eval is evaluated in the context of the String object. Remember that a class name is simply a constant which points to an instance of the class Class. Because of this fact, defining a method in the context of Class instance referenced by String creates a class method for the String class.

Tags: ,