我有这个对象数组:
a = [#<Person id: 9, name: "Bob", bin_id: "114628">,
#<Person id: 10, name: "Sally", bin_id: "114626">,
#<Person id: 11, name: "Jessie", bin_id: "114627">,
#<Person id: 12, name: "Rapheal", bin_id: "114620">,
#<Company _id: 55295, name: "X", bin_id: "114619">,
#<Company _id: 55295, name: "Y", bin_id: "114629">,
#<Company _id: 55295, name: "Z", bin_id: "16074802">,
#<Company _id: 55295, name: "W", bin_id: "16074815">]
当我这样做时
a.group_by { |objects| object.calculate_age }
我明白了:
{
33 =>
[#<Person id: 9, name: "Bob", bin_id: "114628">,
#<Person id: 10, name: "Sally", bin_id: "114626">,
#<Person id: 11, name: "Jessie", bin_id: "114627">],
53 => [#<Company _id: 55295, name: "X", bin_id: "114619">],
45 => [#<Company _id: 55295, name: "Y", bin_id: "114629">,],
56 => [#<Company _id: 55295, name: "Z", bin_id: "16074802">],
60 => [#<Company _id: 55295, name: "W", bin_id: "16074815">]
}
但我如何得到这样的东西:
{
33 => [#<Person id: 9, name: "Bob", bin_id: "114628">],
33 => [#<Person id: 10, name: "Sally", bin_id: "114626">],
33 => [#<Person id: 11, name: "Jessie", bin_id: "114627">],
53 => [#<Company _id: 55295, name: "X", bin_id: "114619">],
45 => [#<Company _id: 55295, name: "Y", bin_id: "114629">,],
56 => [#<Company _id: 55295, name: "Z", bin_id: "16074802">],
60 => [#<Company _id: 55295, name: "W", bin_id: "16074815">]
}
每个键是否明确地设置为每个值?也许group_by
不是正确的方法。我想返回一个像你上面看到的哈希。
答案 0 :(得分:3)
出于问题的目的,您可以编写数组:
arr = [obj0, obj1,...,obj7]
因为每个对象的实例变量的值是无关紧要的。您无法将其转换为具有重复键(age
)的哈希值,但您可以将其转换为哈希数组,每个哈希值都包含一个密钥age
,如果这样做有帮助的话:
arr.map { |obj| { obj.calculate_age=>obj } }
要了解这是如何工作的,假设我们有:
class Friends
attr_reader :calculate_age
def initialize name, age
@name, @calculate_age = name, age
end
end
a = [["Amy", 21], ["Billy-Bob", 53], ["Wilber", 21], ["Trixi", 34], ["Bo", 53]]
arr = a.map { |name,age| Friends.new(name,age) }
#=> [#<Friends:0x007fc1f28b5518 @name="Amy", @calculate_age=21>,
# #<Friends:0x007fc1f28b54a0 @name="Billy-Bob", @calculate_age=53>,
# #<Friends:0x007fc1f28b5450 @name="Wilber", @calculate_age=21>,
# #<Friends:0x007fc1f28b5400 @name="Trixi", @calculate_age=34>,
# #<Friends:0x007fc1f28b5388 @name="Bo", @calculate_age=53>]
我们现在可以将其转换为哈希数组:
a = arr.map { |obj| { obj.calculate_age=>obj } }
#=> [{21=>#<Friends:0x007fc1f28b5518 @name="Amy",...},
# {53=>#<Friends:0x007fc1f28b54a0 @name="Billy-Bob",...},
# {21=>#<Friends:0x007fc1f28b5450 @name="Wilber"...},
# {34=>#<Friends:0x007fc1f28b5400 @name="Trixi"...},
# {53=>#<Friends:0x007fc1f28b5388 @name="Bo",...}]
如果您希望这些数组按年龄排序:
a.sort_by { |h| h.keys.first }
#=> [{21=>#<Friends:0x007fc1f28b5518 @name="Amy",...},
# {21=>#<Friends:0x007fc1f28b5450 @name="Wilber"...},
# {34=>#<Friends:0x007fc1f28b5400 @name="Trixi"...},
# {53=>#<Friends:0x007fc1f28b54a0 @name="Billy-Bob",...},
# {53=>#<Friends:0x007fc1f28b5388 @name="Bo",...}]