Code Like Zell

Using inject for nicer output in IRB

Posted 01 March 2009.

Sometimes you want to inspect an array in irb by iterating through it and printing out some key values, for example:

  events.each do |event|
    puts event.title
  end

But if the array is large, you will first have to scroll up through the returned array to get to your desired printout. We can prevent that by using inject instead:

  events.inject do |x, event|
    puts event.title
  end

Now nil will be returned instead of the events array, and your desired output is in view.

All CLZ Posts

Hide this
Joypad Banner