我正在尝试匹配数组中的键值对并以清晰的格式打印它们:
array = [
{
'name' => 'Tom',
'age' => '31',
'weight' => '180'
},
{
'name' => 'Jane',
'age' => '24',
'weight' => '110'
}
]
array.each do |key, value|
if #{key} == "name"
puts "Name_is=#{key}"
else
puts "#{key}=#{value}"
end
end
这导致:
Name_is={"name"=>"Tom", "age"=>"31", "weight"=>"180"}
{"name"=>"Tom", "age"=>"31", "weight"=>"180"}=
Name_is={"name"=>"Jane", "age"=>"24", "weight"=>"110"}
{"name"=>"Jane", "age"=>"24", "weight"=>"110"}=
预期结果是:
Name_is=Tom
age=31
weight=180
Name_is=Jane
age=24
weight=110
我做得不对?
答案 0 :(得分:4)
你有一个哈希数组,你需要创建一个循环遍历数组的嵌套循环,并且对于数组中的每个哈希,在键/值对上循环:
array.each do |hash|
hash.each do |key, value|
if key == "name"
puts "Name_is=#{key}"
else
puts "#{key}=#{value}"
end
end
end
另外,我不确定为什么你有if #{key} == "name"
而你只能拥有if key == "name"
。
答案 1 :(得分:0)
我认为这是一个类似Ruby的解决方案:
array = [
{
'name' => 'Tom',
'age' => '31',
'weight' => '180'
},
{
'name' => 'Jane',
'age' => '24',
'weight' => '110'
}
]
array.each do |hash|
hash['Name_is'] = hash.delete 'name'
hash.each do |key, value|
puts "#{key}=#{value}"
end
end