Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Mar 29 ’12

Enumerable#each_with_object

Enumerable#each_with_object is quite similar to Enumerable#inject, yet slightly different. From the Ruby 1.9 and Rails 3 API docs:

Iterates the given block for each element with an arbitrary object given, and returns the initially given object.

Iterates over a collection, passing the current element and the memo to the block. Handy for building up hashes or reducing collections down to one object.

evens = (1..10).each_with_object([]) {|i, a| a << i*2 }
#=> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

%w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase }
# => {'foo' => 'FOO', 'bar' => 'BAR'}

As BiHi noted on this tip on Enumerable#inject, its example can be slightly simplified using each_with_object instead of inject:

my_hash = { a: 'foo', b: 'bar' }
# => {:a=>"foo", :b=>"bar"}

my_hash.each_with_object({}) { |(k,v), h| h[k.upcase] = v.upcase }
# => {:A=>"FOO", :B=>"BAR"}

2 notes 0 comments

  1. elegantalgorithm reblogged this from rubyquicktips
  2. rubyquicktips posted this

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus