迭代数组中嵌套哈希中的每个名称

时间:2017-08-15 11:08:35

标签: ruby

我有:

students = [
  {name: "Dr. Hannibal Lecter", cohort: :november},
  {name: "Darth Vader", cohort: :november},
  {name: "Nurse Ratched", cohort: :november},
  {name: "Michael Corleone", cohort: :november},
  {name: "Alex DeLarge", cohort: :november},
  {name: "The Wicked Witch of the West", cohort: :november},
  {name: "Terminator", cohort: :november},
  {name: "Freddy Krueger", cohort: :november},
  {name: "The Joker", cohort: :november},
  {name: "Joffrey Baratheon", cohort: :november},
  {name: "Norman Bates", cohort: :november}
]

我试图循环遍历每个学生的名字:

def print_loop(students)
  puts "Would you like to list the students? 'Y/N'"
  answer = gets.chomp
  while answer != "N" do
    i = students[-1]
    students.each do |student, value|
      puts student[:name]
      break if i
      if answer == "Y"
        exit
      end
    end
  end
end

它只迭代并遍历第一个名称。如何让它迭代每个名字?我做错了什么?

2 个答案:

答案 0 :(得分:2)

如果你必须使用while循环,你可以使用递增计数器和循环,而计数器小于数组的大小

i = 0 

while i < students.size
  puts students[i][:name]
  i += 1
end

请注意,这在ruby中是特殊的,您通常会使用#each循环。

如果你想使用while循环允许用户请求在每个名字之后继续......

i = 0
puts "Would you like to list the students? 'Y/N'"
answer = gets.chomp
while answer == 'Y'
  puts students[i][:name]
  i += 1
  puts "keep going? 'Y/N'"
  answer = gets.chomp
end

答案 1 :(得分:0)

惯用的Ruby方法是:

puts students.collect{ |student| student[:name]}

如果您必须使用while循环,那么您也需要一个计数器i

i = 0
while i < students.size
  puts students[i][:name]
  i += 1
end

如果您还需要提示列表,请在循环外执行。在这里,我还会在方法之外展示它。

def print_loop(students)
  i = 0
  while i < students.size
    puts students[i][:name]
    i += 1
  end
end
puts "Would you like to list the students? 'Y/N'"
answer = gets.chomp.upcase
print_loop(students) if answer == 'Y'