Ruby哈希哈希数组映射

时间:2014-05-26 09:14:53

标签: ruby arrays hash rspec

我有这个哈希,

[{ "player" => { "name" => "Kelvin" , "id" => 1 } , "player" => { "name" => "David",  
   "id" => 2 }]

我检查了每个event是否包含我的Rspec中包含以下行的键[id,name]

json_response.map{|player| ["name","id"].all? {|attribute| player["player"].key? 
  (attribute)}}.should_not include(false) 

完美无缺。如何简化并提高效率?

2 个答案:

答案 0 :(得分:3)

怎么样:

json_response.each do |event|
  event['player'].should have_key('name')
  event['player'].should have_key('id')
end

更清楚的恕我直言

编辑:如果您需要检查很多列:

json_response.each do |event|
  ['name', 'id', 'foo', 'bar', 'baz'].each do |column|
    event['player'].should have_key(column)
  end
end

答案 1 :(得分:0)

根据documentation,您应该可以这样做:

json_response.each do |event|
  event['player'].should include('name', 'id')
end