Krishnaswamy Subramanian

Kirukkalgal - gist on my random thoughts

Ruby: Inject vs Each With Object

| Comments

We all know that inject is very powerful when it comes to:

sum.rb
1
[1,2,3,4,5].inject(0) { |sum, n| sum += n }

Simillary we can use it create a hash from an array

transform.rb
1
2
3
4
5
6
7
8
#using inject
[[:tom,25],[:jerry,15]].inject({}) do |result, name_and_age|
  name, age = name_and_age
  result[name] = age
  result
end

=> {:tom=>25, :jerry=>15}

Now, closely look at line number 5 we are returning the result from the block and this is passed on the enumerator for processing the next object in the array.

We can avoid this extra return statement with the help of Enumerator.each_with_object

transform.rb
1
2
3
4
5
6
7
#using each_with_object
[[:tom,25],[:jerry,15]].each_with_object({}) do |name_and_age, result|
  name, age = name_and_age
  result[name] = age
end

=> {:tom=>25, :jerry=>15}

Comments