Create a hash from a map result

Arnold Roa

I need to create a hash using the key_name and value from a set of results.

It would be clear if I show you what I have:

results.map{|r| {r.other_model.key_name=>r.value} }

that is giving me this:

[{"api_token"=>"stes"}, {"Name"=>"nononono"}]

But I want this:

{"api_token"=>"stes", "Name"=>"nononono"}

What is the most beautiful way to do this on ruby?

Arup Rakshit

Do as below using Hash::[]

Hash[results.map { |r| [r.other_model.key_name,r.value] } ]

In Ruby 2.1.0, we have Hash#to_h

results.map { |r| [r.other_model.key_name,r.value] }.to_h

or use Enumerable#each_with_object

results.each_with_object({}) { |r,h| h[ r.other_model.key_name ] = r.value }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Hash the result from the database , Is it possible?

From Dev

hash map with arraylist and create new arraylist out of it

From Dev

Create hash from variables in loop

From Dev

Create hash from array and frequency

From Dev

How to create a hash from a enumerable?

From Dev

Create hash from variables in loop

From Dev

create a hash from an array in ruby

From Dev

Create JSONArray from array of hash

From Dev

Reproducing the result from Map() with mapply()

From Dev

Return result as Map from JdbcTemplate

From Dev

PHP Password Hash Algorithm Result different from Javascript Result

From Dev

PHP Password Hash Algorithm Result different from Javascript Result

From Dev

Trouble deleting an item from a hash map

From Dev

how to remove duplicate value from hash map

From Dev

Getting a hash from map instead of an array

From Dev

Passing rails hash map to Controller (from form)

From Dev

create Observable<T> from result

From Dev

create a table from result of command

From Dev

create array from mysql result?

From Dev

Create hash with keys from array and a standard value

From Dev

Create XML file from perl hash

From Dev

Create a multidimesional key of hash from array?

From Dev

create an array from a part of a hash in perl

From Dev

How to create a hash from a multidimensional array

From Dev

Create hash structure from .each loop rails

From Dev

Is there any way in angular to create a hash map like structure

From Dev

How to create an immutable map from .map() JS

From Dev

How do you search through a hash mapped from an ActiveRecord result?

From Dev

How to use result from a hash function to get an array index?

Related Related

HotTag

Archive