我有这个问题:
Given the family of hash members, with keys as the title and an array of names as the values, use the Ruby’s built in method to gather immediate family members (“brothers” and “sisters”) only into a new array.
用这个散列:
family = {
uncles:["bob", "joe", "steve"],
sisters: ["jane", "jill", "beth"],
brothers: ["frank", "rob", "david"],
aunts: ["mary", "sally", "susan"]
}
我该怎么做?我什至不确定我需要使用什么内置方法。顺便说一下,我完全是 Ruby 的初学者。
我有这个:
new_family = Array.new
new_family = family.values_at(:brothers, :sisters)
p new_family
这给了我:
[["frank", "rob", "david"], ["jane", "jill", "beth"]]
但我不确定我这样做是否正确?我觉得我可能没有完全理解这个问题?
最佳答案
有许多不同的方法可以做到这一点,您可以简单地执行以下操作:
new_family = family[:brothers] + family[:sisters]
或者,像上面那样:
new_family = family.values_at(:brothers, :sisters).flatten
关于arrays - 在 Ruby 中使用哈希键和值创建新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44856853/