在给定一组键的情况下,将Ruby元组的元组转换为哈希?

Kit*_* Ho 8 ruby arrays

我有一个简单的数组

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

array2 = [["apple", "good taste", "red"], ["orange", "bad taste", "orange"], ["lemon" , "no taste", "yellow"]]
Run Code Online (Sandbox Code Playgroud)

每当数组中的元素与array2中每个元素的第一个元素匹配时,我如何转换为此哈希?

hash = {"apple" => ["apple" ,"good taste", "red"],
        "orange" => ["orange", "bad taste", "orange"], 
        "lemon" => ["lemon" , "no taste", "yellow"] }
Run Code Online (Sandbox Code Playgroud)

我对红宝石很新,并花了很多钱来做这个操作,但没有运气,任何帮助?

Phr*_*ogz 13

如果键和对之间的映射顺序应该基于第一个元素array2,那么您根本不需要array:

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

map = Hash[ array2.map{ |a| [a.first,a] } ]
p map
#=> {
#=>   "apple"=>["apple", "good taste", "red"],
#=>   "lemon"=>["lemon", "no taste", "yellow"],
#=>   "orange"=>["orange", "bad taste", "orange"]
#=> }
Run Code Online (Sandbox Code Playgroud)

如果要使用array选择元素的子集,则可以执行以下操作:

# Use the map created above to find values efficiently
array = %w[orange lemon]
hash  = Hash[ array.map{ |val| [val,map[val]] if map.key?(val) }.compact ]
p hash
#=> {
#=>   "orange"=>["orange", "bad taste", "orange"],
#=>   "lemon"=>["lemon", "no taste", "yellow"]
#=> }
Run Code Online (Sandbox Code Playgroud)

代码if map.key?(val)compact确保在array询问不存在的密钥时是否存在问题array2,并且O(n)及时完成.