Ruby - for循环中的运行时错误

时间:2016-06-18 12:14:59

标签: ruby loops for-loop

我有一个for循环,它会显示存储在数组中的多个哈希值,但只显示与:features键相关的哈希值。

我尝试在ideone.com中运行代码并且for循环工作并打印出我想要的输出,但在第一行显示错误。

#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]

这是我的代码

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

3 个答案:

答案 0 :(得分:3)

您忘记了stderr输出:

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>'

问题是您的循环从0运行到list.length,但list的最后一个有效索引是list.length - 1。这应该有效:

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

更为惯用的方法是使用.each

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

答案 1 :(得分:2)

我认为它会是(...)而不是(..)因为put ...会排除最后一个实际为零的索引

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

答案 2 :(得分:0)

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

index循环中的最后for超出范围。