0

I have this hash,

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

I checked if each event contains the keys [id,name] with the following line in my Rspec,

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

which works perfectly. How can I simplify this and make it more efficient?

2
  • What you show is not a hash. It is not even valid Ruby object. I cannot parse "Array of Hashes of Hashes Map" in your title. Commented May 26, 2014 at 9:27
  • Now, it is a Ruby object, but it is not a hash. Commented May 26, 2014 at 10:02

2 Answers 2

3

How about :

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

Much clearer IMHO

Edit : if you need to check a lot of columns :

json_response.each do |event|
  ['name', 'id', 'foo', 'bar', 'baz'].each do |column|
    event['player'].should have_key(column)
  end
end
Sign up to request clarification or add additional context in comments.

1 Comment

Nice one. But If I need to check like, 10 columns, how can I DRY the code then?
0

According to the documentation you should be able to do this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.