鉴于我有以下哈希数组
@response = { "0"=>{"forename_1"=>"John", "surname_1"=>"Smith"},
"1"=>{"forename_1"=>"Chris", "surname_1"=>"Jenkins"},
"2"=>{"forename_1"=>"Billy", "surname_1"=>"Bob"},
"Status" => 100
}
我希望创建一个forename_1
和surname_1
值组合在一起的数组,因此所需的输出将是
["John Smith", "Chris Jenkins", "Billy Bob"]
所以我可以做到这一点,但需要进一步的帮助
# 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
我在这里做错了什么?
由于
答案 0 :(得分:2)
另一种方式:
@response.values.grep(Hash).map { |t| t.values.join(' ')}
答案 1 :(得分:1)
@response.values.map{ |res|
[res["forename_1"] , res["surname_1"]].join(' ') if res.is_a?(Hash)
}.compact
答案 2 :(得分:1)
你需要做的是获取@response
哈希的值,过滤掉不是Hash
的实例,然后将名字和姓氏连在一起,我会做点什么像这样:
@response.values.grep(Hash).map { |h| "#{h['forename_1']} #{h['surname_1']}" }
# => ["John Smith", "Chris Jenkins", "Billy Bob"]