我有一大堆哈希。我需要做的是从符合特定条件的数组中挑出一个索引哈希。 (这是由于进行了一次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 }
有人知道如何处理这个吗?
答案 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? }