请考虑以下事项:
details = Hash.new
# Example of this Hash's final look
details["team1"] = "Example"
details["team2"] = "Another team"
details["foo"] = "Bar"
我获得两支队伍名称的方式是:
teams = Match.find(1).teams
=> [#<Team id: 1, name: "England">, #<Team id: 2, name: "Australia">]
现在我想将团队名称保存到team1和team2下的Hash中。如果我使用数组我可以做:
teams.each do |team|
details << team.name
end
但是,我需要使用上面显示的哈希来做到这一点。如何实现这一目标?
答案 0 :(得分:4)
Hash[teams.map { |x| ["team_#{x.id}", x.name] }]
# => {"team_1"=>"England", "team_2"=>"Australia"}
如果你想保持id 1和2
Hash[a.map.with_index { |x,i| ["team_#{i.succ}", x.name] }]
# => {"team_1"=>"England", "team_2"=>"Australia"}
答案 1 :(得分:2)
这个怎么样?
teams.each_with_index do |team, idx|
id = "team#{idx + 1}"
details[id] = team.name
end
在这里,您获取团队对象并从中创建哈希键,然后使用该键设置值。
答案 2 :(得分:1)
如何使用单个衬管注射?
teams.inject({}){ |details, team| details["team#{team.id}"] = team.name; details }
返回值将是数组或哈希值。
答案 3 :(得分:0)
{}.tap do |h|
Match.find(1).teams.each_with_index {|t, i| h["team#{i+1}"] = t.name}
end