Jack Kelly - 2 months ago 11

Ruby Question

Is there an alternative to iteration or a condition I can make that will allow me to interpolate the values of just one hash? I've inspected the results of my input and apparently the array that i'm saving my hashes into disappears when there is only one hash. I've also tested the results and they're of Nil class.

`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

How do i solve my problem and also why do hashes behave this way?

Full code:

`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)

Answer

this works for me though, i think with `each_with_index`

enum, you have to pass in an array of hashes i.e. [{...}, {...}, {...}], not a single hash with multiple keys-values

```
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)
```