0

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
2
  • What is your question? Commented Jun 18, 2016 at 12:17
  • I think this error is actually related to running in ideone.com, and not the ruby code itself? Commented Jun 18, 2016 at 12:20

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Using #each is indeed a good choice. I can't remember the last time I used a for loop in Ruby.
2

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

Comments

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

Last index in for loop is out of range.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.