How should I use each_with_object on Hashes?
RubyRuby 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