Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Ruby array of tuples into a hash given an array of keys?

Tags:

arrays

ruby

I have an simple array

array = ["apple", "orange", "lemon"] 

array2 = [["apple", "good taste", "red"], ["orange", "bad taste", "orange"], ["lemon" , "no taste", "yellow"]]

how can i convert in to this hash whenever element in array match the first element of each element in array2?

hash = {"apple" => ["apple" ,"good taste", "red"],
        "orange" => ["orange", "bad taste", "orange"], 
        "lemon" => ["lemon" , "no taste", "yellow"] }

I am quite new to ruby, and spend a lot to do this manipulation, but no luck, any help ?

like image 314
TheOneTeam Avatar asked Jun 08 '12 04:06

TheOneTeam


People also ask

How do you turn an array into a hash in Ruby?

The to_h method is defined in the array class. It works to convert an array to a hash in the form of key-value pairs. The method converts each nested array into key-value pairs. The method also accepts a block.

How do you push values into an array of hash in Ruby?

Creating an array of hashes You are allowed to create an array of hashes either by simply initializing array with hashes or by using array. push() to push hashes inside the array. Note: Both “Key” and :Key acts as a key in a hash in ruby.

What is the difference between a hash and an array in Ruby?

Ruby's arrays and hashes are indexed collections. Both store collections of objects, accessible using a key. With arrays, the key is an integer, whereas hashes support any object as a key.

Does Ruby support tuples?

In Python a Tuple is used with parenthesis (1,2,3). In Ruby things aren't as fixed so you don't have Tuples as a common things to access.


1 Answers

Paired Tuples to Hash Example

fruit_values = [
  ['apple', 10],
  ['orange', 20],
  ['lemon', 5]
]

fruit_values.to_h
# => {"apple"=>10, "orange"=>20, "lemon"=>5} 

I decided I would leave this answer here for anyone looking to convert paired tuples into a hash.

Although it is slightly different from the question, this is where I landed on my Google search. It also matched up a bit with the original question due to the array of keys being already in the tuples. This also doesn't put the key into the value which the original question wanted, but I honestly wouldn't duplicate that data.

like image 181
CTS_AE Avatar answered Sep 21 '22 13:09

CTS_AE