Kevin Kevin - 5 months ago 15
Ruby Question

Ruby - Runtime error in for loop

I have a for loop that would display a number of hashes stored in an array but only those associated to the :features key.

I tried running the code in ideone.com and the for loop works and prints out my desired output but on the very first line it displays an error.

#output
Runtime error time: 0.06 memory: 9712 signal:-1
[0.25, 0.1, 5]
[0.3, 0.14, 7]
[0.2, 0.17, 6]
[0.4, 0.12, 8]
[0.1, 0.11, 3]


And here is my code

data_point_a = {:label => "cat", :features => [0.25,0.1,5]}
data_point_b = {:label => "dog", :features => [0.3,0.14,7]}
data_point_c = {:label => "dog", :features => [0.2,0.17,6]}
data_point_d = {:label => "dog", :features => [0.4,0.12,8]}
data_point_e = {:label => "cat", :features => [0.1,0.11,3]}
data_point_f = {:label => "unknown", :features => [0.8,0.3,4]}
#data point f is not part of the array
list = [data_point_a, data_point_b,data_point_c,data_point_d,data_point_e]

for index in 0..list.length
puts "#{list[index][:features]}"
end

Answer

You forgot to see the stderr output:

prog.rb:11:in `block in <main>': undefined method `[]' for nil:NilClass (NoMethodError)
    from prog.rb:10:in `each'
    from prog.rb:10:in `<main>'

The problem is that your loop runs from 0 to list.length, but the last valid index of list is list.length - 1. This should work:

for index in 0..(list.length - 1)
    puts "#{list[index][:features]}"
end

A more idiomatic way to do this would be to use .each:

list.each do |item|
  puts "#{item[:features]}"
end