【发布时间】:2017-03-10 20:32:20
【问题描述】:
是否有替代迭代的方法或我可以设置的条件允许我只插入一个哈希的值?我检查了输入的结果,显然当只有一个哈希时,我保存哈希的数组消失了。我还测试了结果,它们属于 Nil 类。
def print_with_index(students)
students.each_with_index do |student, index|
index_plus_one = index + 1
puts "#{index_plus_one}. #{students[:name]} (#{students[:cohort]} cohort)"
end
end
我如何解决我的问题以及为什么哈希会这样?
完整代码:
def print_header
puts "The students of Villains Academy"
puts "--------------"
end
def print_footer(names)
puts "Overall, we have #{names.count} great students"
end
def input_students
puts "Please enter the names and then the cohort of the students"
puts "To finish, just hit return twice"
#created an empty array
students = []
#getting the first name
name = gets.chomp
cohort = gets.chomp.to_sym
if cohort.empty?
cohort = :november
end
if cohort !~ /january|february|march|april|may|june|july|august|september|october|november|december/
puts "Please enter a valid month"
puts "Warning months are case sensitive. Please enter in lowercase characters."
cohort = gets.chomp.to_sym
end
while !name.empty? do
# add the student hash to the array called students
students << {name: name, cohort: cohort}
if students.count > 1
puts "Now we have #{students.count} students"
else students.count == 1
puts "Now we have #{students.count} student"
end
#getting another name from the user
name = gets.chomp
cohort = gets.chomp.to_sym
if cohort.empty?
cohort = :november
end
if cohort !~ /january|february|march|april|may|june|july|august|september|october|november|december/
puts "Please enter a valid month"
puts "Warning months are case sensitive. Please enter in lowercase characters."
cohort = gets.chomp.to_sym
end
end
bycohort = students.sort_by { |v| v[:cohort] }
filter = students.select! { |student| student[:cohort] == :november }
puts bycohort #This allows me to see all of my hashes before they are filtered
puts ""
bycohort
filter
end
def print_with_index(students)
students.each_with_index do |students, index|
index_plus_one = index + 1
puts "#{index_plus_one}. #{students[:name]} (#{students[:cohort]} cohort)"
end
end
### body ###
students = input_students
print_header
print_with_index(students)
print_footer(students)
【问题讨论】:
-
each_with_index块的第一个参数应该是student(单数)以避免混淆。此外,字符串插值中#{...}中的内容是任何Ruby 表达式,所以"#{index + 1}. #{student[:name]}..."很好。 -
当我尝试调用 print_with_index 方法时,我的代码仍然出现 NilClass 错误。即使我进行了 Sean 的更改并更改了我的姓名和群组变量的范围并显式打印。
标签: ruby hash iterator iteration string-interpolation