Home > Mobile >  For the life of me I can't get this to print the "hobbies" on individual lines?
For the life of me I can't get this to print the "hobbies" on individual lines?

Time:09-16

 people = [
  {
    "first_name" => "Robert",
    "last_name" => "Garcia", 
    "hobbies" => ["basketball", "chess", "phone tag"]
   },
  {
    "first_name" => "Molly",
    "last_name" => "Barker",
    "hobbies" => ["programming", "reading", "jogging"]
   },
  {
    "first_name" => "Kelly",
    "last_name" => "Miller",
    "hobbies" => ["cricket", "baking", "stamp collecting"]
   }
]

index = 0
while  index < "hobbies".length
  p people[index]["hobbies"]
  index  = 1
end

with the class I'm taking they want me to use the p statement not puts and it wants me to run it as a loop I don't understand what the "undefined method '[]'" is can anyone shine some light on this and walk me through it as simply as possible? Any help is greatly appreciated

CodePudding user response:

You are attempting to iterate through people based on the length of the string "hobbies". Now, that string has length 7, but the people array only has length 3.

You either want:

index = 0
while  index < people.length
  p people[index]["hobbies"]
  index  = 1
end

Or better is to just used the each method.

people.each do |person|
  p person["hobbies"]
end

When I run this, I see:

irb(main):028:0> people.each do |person|
irb(main):029:1*   p person["hobbies"]
irb(main):030:1> end
["basketball", "chess", "phone tag"]
["programming", "reading", "jogging"]
["cricket", "baking", "stamp collecting"]

The reason you get the error you do can be shown with a very simple example:

irb(main):001:0> a = [2]
=> [2]
irb(main):002:0> a.length
=> 1
irb(main):003:0> a[0]
=> 2
irb(main):004:0> a[1]
=> nil

When we access an array at an index that's out of bounds, we don't get an error. We just get nil. In your code, you try to subscript nil and that does cause the error you're seeing.

  • Related