Есть ли альтернатива итерации или условие, которое я могу сделать, что позволит мне интерполировать значения только одного хэша? Я проверил результаты моего ввода и, по-видимому, массив, в котором я сохраняю свои хэши, исчезает, когда есть только один хеш. Я также тестировал результаты, и они из класса 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' должен быть« учеником »(единственным), чтобы избежать путаницы. Кроме того, материал внутри '# {...}' в строковой интерполяции есть любое выражение Ruby, поэтому '' # {index + 1}. # {Student [: name]} ... "' отлично. –
Я по-прежнему получаю ошибки NilClass для своего кода, когда пытаюсь вызвать метод print_with_index. Даже если я сделаю изменения Шона и изменю масштаб моего имени и когортных переменных и напечатаю явно. –