arrays - 在 Ruby 中使用哈希键和值创建新数组

标签 arrays ruby hash

我有这个问题:

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/

相关文章:

java - 将变量分配给数组无法正常工作(Java)

php - 清理密码的正确方法是什么?

java - Linux 命令行 SHA-256 哈希与在线工具不同?

ruby - 组哈希值-Ruby

Javascript 数组声明(可能误用了长度属性?)

javascript - 使用 lodash 使用一些更新和删除的结果更新数组的最佳方法是什么?

java - 编写 int 数组并返回元素数量的正确方法?

javascript - 如何防止 sprockets 缓存 .erb 文件?

ruby - 使用变量的 Object.const_set

ruby - each_with_index block 中的 i 是什么