Need help accessing data from array in a hash

Here is a sample of my code. It does not exactly work but I am hoping that it is enough to show what I am trying to do.

student_list = {
        'joe' => [ '150lbs','brown','black' ],
        'bob' => [ '175lbs','blue','blonde'],
        'ray' => [ '165lbs','green','red']
student_list.each do |name=>[weight,eye_color,hair_color]|
  puts "student name:  #{name}"
  puts "student's weight:  #{weight}"
  puts "student's eye color:  #{eye_color}"
  puts "student's hair color:  #{hair_color}"

Help. :slight_smile:


I just figured this out by using

student_list.each do |name,traits|

puts "student’s weight: " + traits[0]

'Hope this helps. :slight_smile:

A hash isn’t a great choice here, because as soon as you have two students with the same name, the data get overwritten. What you really have is a set of student records so an array of arrays might be more suitable.

student_list = [
  %w[Joe 150lbs brown black],
  %w[Bob 175lbs blue blonde],
  %w[Ray 165lbs green red],
  %w[Joe 200lbs blue black]

def list_students(list)
  list.each do |student|
    name, weight, eyes, hair = student
    puts "#{name} weighs #{weight} and has #{hair} hair and #{eyes} eyes"

list_students student_list


you are right. that is an even better implementation of what i am trying to accomplish.



This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs