抓取符合特定条件的数组中的特定哈希

时间:2017-03-17 15:27:05

标签: ruby-on-rails arrays ruby hash

我有一大堆哈希。我需要做的是从符合特定条件的数组中挑出一个索引哈希。 (这是由于进行了一次rspec测试,但是在挑出其中一个时遇到了麻烦)

我的数组就像这样

[
  {
                      "name" => "jon doe",
                     "team" => "team2",
                     "price" => 2000,
      "eligibility_settings" => {}
  },
  {
                      "name" => "jonny doe",
                     "team" => "team1",
                     "value" => 2000,
      "eligibility_settings" => {
                     "player_gender" => male,
                    "player_max_age" => 26,
                    "player_min_age" => 23,
          "established_union_only" => true
      }
  },
  {
                      "name" => "jonni doe",
                     "team" => "team3",
                     "price" => 2000,
      "eligibility_settings" => {}
  },  
]

我需要根据其资格设置挑出第二个。我刚刚从我的数组中取出了三个,还有更多,所以像这样简单的主动记录方法(hash.second)在这个实例中不起作用。

我尝试过像

这样的事情
players.team.map(&:hash).find{ |x| x[ 'eligibility_settings?' ] == true}

但是,当我尝试此操作时,我收到nil响应。 (这很奇怪)

我也研究过使用红宝石detect方法,这种方法还没有让我到任何地方

Players.team.map(&:hash).['hash.seligibiltiy_settings'].detect { true }

有人知道如何处理这个吗?

1 个答案:

答案 0 :(得分:0)

注释

players.team.map(&:hash).find{ |x| x[ 'eligibility_settings?' ] == true}
Players.team.map(&:hash).['hash.seligibiltiy_settings'].detect { true }
  • players还是Players
  • 为什么会复数?
  • 如果您可以在map上致电team,则可能应该是复数
  • 为什么要转换为哈希?
  • eligibility_settings?不是哈希中的密钥。 eligibility_settings
  • eligibility_settings可以是哈希值,但不能是true
  • 如果您想检查它是否为空,请使用!h['eligibility_settings'].empty?

可能的解决方案

您可以使用:

data = [
  {
    'name' => 'jon doe',
    'team' => 'team2',
    'price' => 2000,
    'eligibility_settings' => {}
  },
  {
    'name' => 'jonny doe',
    'team' => 'team1',
    'value' => 2000,
    'eligibility_settings' => {
      'player_gender' => 'male',
      'player_max_age' => 26,
      'player_min_age' => 23,
      'established_union_only' => true
    }
  },
  {
    'name' => 'jonni doe',
    'team' => 'team3',
    'price' => 2000,
    'eligibility_settings' => {}
  }
]

p data.find { |h| !h['eligibility_settings'].empty? }

# {"name"=>"jonny doe", "team"=>"team1", "value"=>2000, "eligibility_settings"=>{"player_gender"=>"male", "player_max_age"=>26, "player_min_age"=>23, "established_union_only"=>true}}

如果h['eligibility_settings']可以是nil,您可以使用:

data.find { |h| !h['eligibility_settings'].blank? }

data.find { |h| h['eligibility_settings'].present? }