Reputation: 15374
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
Upvotes: 1
Views: 69
Reputation: 19230
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"]
Upvotes: 1
Reputation: 3072
Another way :
@response.values.grep(Hash).map { |t| t.values.join(' ')}
Upvotes: 2
Reputation: 73589
@response.values.map{ |res|
[res["forename_1"] , res["surname_1"]].join(' ') if res.is_a?(Hash)
}.compact
Upvotes: 1