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 ?
If the order of the mapping between the key and pairs should be based on the first element in
array2, then you don’t needarrayat all:If you want to use
arrayto select a subset of elements, then you can do this:The code
if map.key?(val)andcompactensures that there is not a problem ifarrayasks for keys that are not present inarray2, and does so inO(n)time.