Ruby on rails 通过permaiters访问散列中的数组中的散列

Ruby on rails 通过permaiters访问散列中的数组中的散列,ruby-on-rails,ruby,json,hash,Ruby On Rails,Ruby,Json,Hash,我想知道第一个射手的名字。问题是数据在下面的散列中的数组中,然后我需要测试它,看看它是否是目标 有什么想法吗 数据: 如果你有一场比赛的数据,你可以得到第一个进球得分者,如下所示: goal_incident = match['incidents'].detect{|i| i['type'] == 'Goal'} if goal_incident puts "First goal scorer was #{goal_incident['playershort']}" else puts

我想知道第一个射手的名字。问题是数据在下面的散列中的数组中,然后我需要测试它,看看它是否是目标

有什么想法吗

数据:


如果你有一场比赛的数据,你可以得到第一个进球得分者,如下所示:

goal_incident = match['incidents'].detect{|i| i['type'] == 'Goal'}
if goal_incident
  puts "First goal scorer was #{goal_incident['playershort']}"
else
  puts "There were no goals :("
end

您的解决方案还可以,但速度稍慢。当您使用
select
ruby必须遍历整个数组,如果您只对第一个目标感兴趣,那么这是不必要的。当您使用
detect
时,循环在找到第一个目标后结束。

这就是我最终解决问题的方法:

有重构的想法吗

json.each do |result|
  score = result["fulltime"]
  goals = result['incidents'].select do |incidents|
    incidents['goaltype'] != nil
  end

  if goals.count >= 1
    first_goalscorer_player_name = goals.first['playershort'] 
  else 
    first_goalscorer_player_name = "No Goal Scorer"
  end

你需要在我要展示给你的另一个循环中使用.each循环,但是代码很难读懂。你能链接控制器吗?编辑后看起来好多了,我相应地更新了答案并添加了重构解释。
json.each do |result|
  score = result["fulltime"]
  goals = result['incidents'].select do |incidents|
    incidents['goaltype'] != nil
  end

  if goals.count >= 1
    first_goalscorer_player_name = goals.first['playershort'] 
  else 
    first_goalscorer_player_name = "No Goal Scorer"
  end