我试图在每个子数组中提取三个值,但它似乎不起作用。返回的对象是否有异常,或者我的数组提取代码是否不正确?
#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
输出
king@death-star ~/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>'
答案 0 :(得分:1)
数组数组的第一个元素是nil
,而nil
没有方法[]
。您可以使用compact
方法删除nil
元素。
http://docs.ruby-lang.org/en/2.0.0/Array.html#method-i-compact
答案 1 :(得分:1)
根据您的输出,output
变量的第一个值为nil
,您可以使用compact
:
返回self的副本,删除所有nil元素。
temp.output.compact.each do |x|
puts "#{x[0]},#{x[1]},#{x[2]}"
end