鉴于我有以下哈希数组
@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
我做错了什么?
谢谢
最佳答案
另一种方式:
@response.values.grep(Hash).map { |t| t.values.join(' ')}
关于ruby - 从 Ruby 哈希数组中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29679184/