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?
The each_with_object function in Ruby is used to Iterate the given object's each element. Syntax: A.each_with_object({}) Here, A is the initialised object. Parameters: This function does not accept any parameters. Returns: the new set of values.
Iterating over a Hash You can use the each method to iterate over all the elements in a Hash. However unlike Array#each , when you iterate over a Hash using each , it passes two values to the block: the key and the value of each element.
Use ()
:
hash.each_with_object([]) { |(k, v), array| array << k }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With