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 ?
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.
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.
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.
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.
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.
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