试图将每个转换为 while 循环,创建 TypeError。为什么符号有问题?

Trying to convert each to while loop, creates TypeError. Why is it having a problem with symbols?

我有一个完成的程序,但现在我需要将#Each 循环转换为#While 循环。循环应该输出几乎相同的信息,但它抛出一个 'directory.rb:24:in `print': no implicit conversion of Symbol into Integer (TypeError)' instead.

def input_students
  puts "Please enter the names of the students"
  puts "To finish, just hit return twice"
  students = []
  name = gets.chomp
  while !name.empty? do
    students << {name: name, cohort: :november}
    puts "Now we have #{students.count} students"
    name = gets.chomp
  end
  students
end

students = input_students

def print_header
  puts "The students of Villains Academy"
  puts "----------"
end

def print(students)
  students.each.with_index(1) do |students, index|
    puts "#{index} #{students[:name]}, #{students[:cohort]} cohort"
  end
end

def print_footer(names)
  puts "Overall we have #{names.count} great students"
end


print_header
print(students)
print_footer(students)

按预期工作。我正在尝试:

def print(students)
  i = 0
  while i < students.length
    puts "#{students[:name]}, #{students[:cohort]} cohort"
  end
end

为什么 #While 循环不能处理类似的输入,为什么要尝试转换为整数?

  while i < students.length
    puts "#{students[:name]}, #{students[:cohort]} cohort"
  end

students 是一个数组。你不能用符号来处理它的元素。您需要做的是使用 i 获取学生的 元素 。您可以在上面调用 [:name]

我认为这个错误来自于这段代码中糟糕的命名。 And/or 不明白 each 是如何工作的。

students.each.with_index(1) do |students, index|  
#                                ^^^^^^
#  This here is called `students`, but its value is a single student, 
#  not a collection of students.

因为您的 #each 循环正在隐藏 students 变量:

# v                              v
students.each.with_index(1) do |students, index|
  puts "#{index} #{students[:name]}, #{students[:cohort]} cohort"
end

您迭代一个名为 students 的数组,然后将数组中的每个元素分配给一个名为 students 的变量。当您摆脱 each 循环时,您并没有更改块以停止查看 students,因此它现在正在查看数组。要获取单个元素,请尝试:

def print(students)
  i = 0
  while i < students.length
    puts "#{students[i][:name]}, #{students[i][:cohort]} cohort"
  end
end