2016-10-28 4 views
0

Есть ли альтернатива итерации или условие, которое я могу сделать, что позволит мне интерполировать значения только одного хэша? Я проверил результаты моего ввода и, по-видимому, массив, в котором я сохраняю свои хэши, исчезает, когда есть только один хеш. Я также тестировал результаты, и они из класса 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) 
+1

Первый аргумент блока 'each_with_index' должен быть« учеником »(единственным), чтобы избежать путаницы. Кроме того, материал внутри '# {...}' в строковой интерполяции есть любое выражение Ruby, поэтому '' # {index + 1}. # {Student [: name]} ... "' отлично. –

+0

Я по-прежнему получаю ошибки NilClass для своего кода, когда пытаюсь вызвать метод print_with_index. Даже если я сделаю изменения Шона и изменю масштаб моего имени и когортных переменных и напечатаю явно. –

ответ

1

это работает для меня, хотя, я думаю, что с each_with_index перечислимого, вы должны передать в массив хэшей, то есть [{...}, {...}, { ...}], ни один хэш с несколькими ключами значений

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 

print_with_index([{name:"b", cohort: "c"}]) 
# 1. b (c cohort) 
+0

Ahh ок. Но что, если я не знаю, какой будет ценность каждого из них? Пользователь будет вводить значения хэша. –

+0

Что вы подразумеваете, не зная значения ввода пользователя? я думаю, что все в порядке, пока ключ совпадает (i..e 'name' &' cohort') ваша интерполяция '... [: name]' & '... [: когорт]', и входы хранится как хэш в массиве –

+0

Ahh, все в порядке. Я забыл об области в течение нескольких минут. Я могу просто добавить несколько @s в свой метод ввода. Я все же получаю ошибки NilClass. Я добавил свой полный код, если вы хотите его проверить. –

0

Вы должны использовать student вместо students в качестве параметра блока. Вы можете проверить, является ли объект-ученик nil.

def print_with_index(students) 

    students.each_with_index do |student, index| 
    if !student.nil? 
     index_plus_one = index + 1 
     puts "#{index_plus_one}. #{student[:name]} (#{student[:cohort]} cohort)" 
    end 
    end 
end 
+0

Если объект равен нулю (один хеш), но я все еще хочу это для интерполяции на мой шаблон строки. Могу ли я это сделать? И спасибо за предложение, я изменю параметр блока. –

+0

Если возможно, попробуйте использовать меньше жаргона. Например, трудно понять, что вы подразумеваете под «Если объект« ниль »(один хеш)». Если объект «nil», то это именно так. Это не хэш. –

+0

... Но в любом случае, если переменная равна нулю, вы можете распечатать строку '' # {nil} "'. –