rubyruby-on-rails-4rubygems

What each_with_object does in ruby


What each_with_object does? Where it get opts? https://github.com/bodrovis/lokalise_manager/blob/master/lib%2Flokalise_manager%2Ftask_definitions%2Fbase.rb#L23

primary_opts = global_config
                 .singleton_methods
                 .filter { |m| m.to_s.end_with?('=') }
                 .each_with_object({}) do |method, opts|
  reader = method.to_s.delete_suffix('=')
  opts[reader.to_sym] = global_config.send(reader)
end
# *your text*

Tryed to the rear docs on ruby website


Solution

  • each_with_object iterates the enumerable in the similar way as each does.

    But allows you to pass an additional object to the block (like an empty hash in this example) and it returns that object at the end (and not the iterator as each would do).

    This is a simplified example. Instead of

    hash = {}
    [1, 2, 3].each do |number|
      hash[number] = number * number
    end
    hash
    #=> { 1 => 1, 2 => 4, 3 => 9 }
    

    each_with_object allows you to write:

    [1, 2, 3].each_with_object({}) do |number, hash|
      hash[number] = number * number
    end
    #=> { 1 => 1, 2 => 4, 3 => 9 }