我无法获取代码以正确显示有关人员的信息。我可以列出姓名,但不能列出年龄。
my_group = ["person_1", "person_2", "person_3"]
person_1 = {name: "erik", gender: "male", age: 26}
person_2 = {name: "erika", gender: "female", age: 26}
person_3 = {name: "erka", gender: "alpha", age: 27}
my_group.each do |name|
my_group.each do |age|
puts "Hello, #{name} is about #{age} years old"
end
puts "Hello, #{name} is about #{age} years old"
end
我没有收到错误代码,但没有列出年龄和姓名。
答案 0 :(得分:4)
实际上,您的my_group
仅包含Strings
。如果要包含人员变量,则可以将其作为变量(不包含""
)包含
person_1 = {name: "erik", gender: "male", age: 26}
person_2 = {name: "erika", gender: "female", age: 26}
person_3 = {name: "erka", gender: "alpha", age: 27}
my_group = [ person_1, person_2, person_3 ]
然后,您可以使用Array#each
方法将每个人循环到该数组中。
my_group.each do |person|
puts "Hello, #{person[:name]} is about #{person[:age]} years old"
end
还要注意,每个人都是Hash
。例如,如果要访问person_1
的年龄属性,则必须执行以下操作:
puts person_1[:name]