Kevin
Kevin

Reputation: 171

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

Upvotes: 0

Views: 170

Answers (3)

Parnab Sanyal
Parnab Sanyal

Reputation: 739

I think it will be ... instead of .. because putting ... will exclude the last index which is actually nil

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

Upvotes: 2

pjanek
pjanek

Reputation: 76

(0..3).to_a     #=> [0,1,2,3]
(0...3).to_a    #=> [0,1,2]

Last index in for loop is out of range.

Upvotes: 0

Dogbert
Dogbert

Reputation: 222080

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

Upvotes: 3

Related Questions