people = [
{ "name" => "Mary", "sport" => "squash", "fruit" => "blackberry" },
{ "name" => "Lauren", "sport" => "squash", "fruit" => "orange" },
{ "name" => "Isla", "sport" => "weightlifting", "fruit" => "banana" },
{ "name" => "Sam", "sport" => "cycling", "fruit" => "orange" },
{ "name" => "Govind", "sport" => "squash", "fruit" => "banana" },
{ "name" => "Awad", "sport" => "weightlifting", "fruit" => "kiwi" },
{ "name" => "Will", "sport" => "cycling", "fruit" => "blackberry" }
]
sport = {
squash: [],
weightlifting: [],
cycling: []
}
根据人们所选择的运动来分组,最简单的方法是什么?
I.e.
sport = {
squash: ["Mary", "Lauren", "Govind"],
weightlifting: ["Isla", "Awad"],
cycling: ["Sam", "Will"]
}
事实上,哈希里面有哈希,这让我很困惑。我现在正在玩下面的,但还没有雪茄。
sport[:squash].push(people.select {|k,v| k if v == "squash"})
2条答案
按热度按时间rta7y2nd1#
像这样的吗
我已经使用了group_by和transform_values,阅读了关于它们的文档。
group_by
是在Enumerable
上调用的(这是Array
,Hash
和其他模块中包含的模块),transform_values
是在Hash
上调用的。一次执行一个方法以更好地理解发生了什么。q7solyqu2#
您可以按如下方式填写散列
sport
。如果
sport
的密钥是未知的,并且要从people
导出,则可以按如下方式进行。常见的是以以下两种方式之一缩短:
或
后者使用Hash::new的形式,使用一个块。