1

Given that I have the following array of hashes

@response =  { "0"=>{"forename_1"=>"John", "surname_1"=>"Smith"}, 
               "1"=>{"forename_1"=>"Chris", "surname_1"=>"Jenkins"}, 
               "2"=>{"forename_1"=>"Billy", "surname_1"=>"Bob"},
               "Status" => 100
             }

I am looking to create an array of the forename_1 and surname_1 values combined, so desired output would be

["John Smith", "Chris Jenkins", "Billy Bob"]

So I can get this far, but need further assistance

# Delete the Status as not needed
@response.delete_if { |k| ["Status"].include? k }

@response.each do |key, value|
  puts key
  #This will print out 0 1 2
  puts value
  # This will print {"forename_1"=>"John", "surname_1"=>"Smith"}, "{"forename_1"=>"Chris", "surname_1"=>"Jenkins"}, "{"forename_1"=>"Billy", "surname_1"=>"Bob"}
  puts value.keys
 # prints ["forename_1", "surname_1"], ["forename_1", "surname_1"], ["forename_1", "surname_1"] 
  puts value.values
  # prints ["John", "Smith"], ["Chris", "Jenkins"], ["Billy", "Bob"] 
  value.map { |v| v["forename_1"] }
  # However i get no implicit conversion of String into Integer error
end

What am i doing wrong here?

Thanks

3 Answers 3

2

Another way :

@response.values.grep(Hash).map { |t| t.values.join(' ')}
Sign up to request clarification or add additional context in comments.

1 Comment

Only works if he KNOWS that the values of that hash always comes in that order. The order is fixed in ruby but the data might come from other sources.
1

What you have to do is to get the values of the @response hash, filter out what is not an instance of Hash, and then join together the forename and the surname, I would do something like this:

@response.values.grep(Hash).map { |h| "#{h['forename_1']} #{h['surname_1']}" }
# => ["John Smith", "Chris Jenkins", "Billy Bob"]

1 Comment

Thanks, that's a neat way of putting it together
1
@response.values.map{ |res| 
   [res["forename_1"] , res["surname_1"]].join(' ')  if res.is_a?(Hash)  
}.compact

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.