尝试将每个转换为 while 循环,会创建类型错误.为什么它的符号有问题



我有一个完成的程序,但现在我需要将 #Each 循环转换为 #While 循环。循环应该输出几乎相同的信息,但它抛给我一个"directory.rb:24:in 'print':没有将符号隐式转换为整数(TypeError)"。

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 循环不能处理类似的输入,为什么它试图转换为整数?

因为你的#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
  while i < students.length
    puts "#{students[:name]}, #{students[:cohort]} cohort"
  end

students是一个数组。不能使用符号来寻址其元素。您需要做的是使用i来获取学生的元素。你可以打电话给[:name]

我认为,错误来自此片段中糟糕的命名。和/或不了解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.

相关内容

最新更新