The documentation says:
Iterates the given block for each element with an arbitrary object, obj, and returns obj
Iterates the given block for each element with an arbitrary object, obj, and returns obj
But when I tried the below on the both constructs, one gave me the output as expected but the others didn’t. So I suspect there is a difference between those two constructs.
Using each_with_object
%w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase }
=> {"foo"=>"FOO", "bar"=>"BAR"}
success here!
Using with_object
%w(foo bar).with_object({}) { |str, hsh| hsh[str] = str.upcase }
=> NoMethodError: undefined method `with_object' for ["foo", "bar"]:Array
from (irb):1
from C:/Ruby193/bin/irb:12:in `<main>'
failed here!
So what is the difference between these two methods?
eachreturns an Enumerator object.So, for the first case, the array’ll be converted to
Enumeratorfirst, then works on thewith_object.If you want the second case works, you have to convert the array to Enumerator. You can use
.to_enum,.each, or.mapto convert the array.More details: Enumerator