Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I use each_with_object on Hashes?

Tags:

ruby

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?

like image 805
Pierre-Louis Gottfrois Avatar asked Aug 16 '13 13:08

Pierre-Louis Gottfrois


People also ask

What is Each_with_object Ruby?

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.

How do I iterate a hash in Ruby?

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.


1 Answers

Use ():

hash.each_with_object([]) { |(k, v), array| array << k } 
like image 123
apneadiving Avatar answered Sep 29 '22 05:09

apneadiving