Ruby Each With Object

Last Updated On Tuesday 25th Jan 2022

each_with_object

  • Iterates the given block for each element with an arbitrary object given and returns the initially given object.
  • If no block is given, returns an enumerator.
	each_with_object(obj) { |(*args), memo_obj| ... } → obj
	

each with object ruby

  • The syntax of .each_with_object is consistent with .each_with_index.
  • Where the element is, the first parameter is an object.
  • Element with The Second parameter is an index.

Example 1 Enumerable each_with_object in a hash

	{ a: “Sam”, b: “Mali”, c: “Cira” }.each_with_object([]) do |pair, array|
  array << pair.last
end
# => [“Sam”, “Mali”, “Cira”]
	
  • Also can capture the key and value in the block.
	{ a: “Sam”, b: “Mali”, c: “Cira” }.each_with_object([]) do |(key, value), hash|
  hash[value] = key
end
# => { "Sam" => :a, "Mali" => :b, "Cira" => :c }
	

Example 2

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

Example 3

	nums = [1, 1, 2, 3, 3, 5]
nums.each_with_object(Hash.new(0)) { |e, a| a[e] += 1 }
# => {1=>2, 2=>1, 3=>2, 5=>1}
	

Reference Link