How should I use each_with_object on Hashes?

Ruby

Ruby Problem Overview


I would like to use each_with_object on a hash but can't figure out how I should use it. Here is what I have:

hash = {key1: :value1, key2: :value2}
hash.each_with_object([]) { |k, v, array| array << k }

NoMethodError: undefined method `<<' for nil:NilClass

Is it possible to use each_with_object on hashes? If yes, what is the syntax?

Ruby Solutions


Solution 1 - Ruby

Use ():

hash.each_with_object([]) { |(k, v), array| array << k }

Solution 2 - Ruby

I have idea about that. You can use

output =[]
Hash.each_with_index do |e, index| 
  // do something with e. E is aray. e have 2 items.
  // First item of e is key.
  // Last item of e is value.
  // index start with 0.
  // using << with output here.
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPierre-Louis GottfroisView Question on Stackoverflow
Solution 1 - RubyapneadivingView Answer on Stackoverflow
Solution 2 - RubyThienSuBSView Answer on Stackoverflow