2016-06-10 126 views
0

我想提取每个子数组中的三个值,但似乎不起作用。对于返回的对象是否有不寻常的现象,或者我的数组提取代码不正确?从数组中提取值

#https://github.com/Nedomas/indicators 
require 'active_support' 
require 'active_support/core_ext' 
require 'indicators' 

my_data = Indicators::Data.new([1,2,3,4,3,2,4,6,1,2]) 
temp=my_data.calc(:type => :bb, :params => 2) 
puts temp.inspect 
temp.output.each do |x| puts "#{x[0]},#{x[1]},#{x[2]}" end 

输出

[email protected] ~/Desktop/_REPOS/misc/stock_analysis/forex/oanda/ruby $ ruby temp.rb 
#<Indicators::Main:0x00000002c1f9b0 @abbr="BB", @params=[2, 2], @output=[nil, [1.5, 2.914213562373095, 0.08578643762690485], [2.5, 3.914213562373095, 1.0857864376269049], [3.5, 4.914213562373095, 2.085786437626905], [3.5, 4.914213562373095, 2.085786437626905], [2.5, 3.914213562373095, 1.0857864376269049], [3.0, 5.82842712474619, 0.1715728752538097], [5.0, 7.82842712474619, 2.1715728752538097], [3.5, 10.571067811865476, -3.5710678118654755], [1.5, 2.914213562373095, 0.08578643762690485]]> 
temp.rb:9:in `block in <main>': undefined method `[]' for nil:NilClass (NoMethodError) 
    from temp.rb:9:in `each' 
    from temp.rb:9:in `<main>' 

回答

1

根据您的输出output变量的第一个值是nil,你可以使用compact

返回自己的副本,其中删除了所有零元素。

temp.output.compact.each do |x| 
    puts "#{x[0]},#{x[1]},#{x[2]}" 
end