Here is the code I’m working with:
class Trader
def initialize(ticker ="GLD")
@ticker = ticker
end
def yahoo_data(days=12)
require 'yahoofinance'
YahooFinance::get_historical_quotes_days( @ticker, days ) do |row|
puts "#{row.join(',')}" # this is where a solution is required
end
end
end
The yahoo_data method gets data from Yahoo Finance and puts the price history on the console. But instead of a simple puts that evaporates into the ether, how would you use the preceding code to populate an array that can be later manipulated as object.
Something along the lines of :
do |row| populate_an_array_method(row.join(',') end
If you don’t give a block to
get_historical_quotes_days, you’ll get an array back. You can then usemapon that to get an array of the results ofjoin.In general since ruby 1.8.7 most iterator methods will return an enumerable when they’re called without a block. So if
foo.bar {|x| puts x}would print the values 1,2,3 thenenum = foo.barwill return an enumerable containing the values 1,2,3. And if you doarr = foo.bar.to_a, you’ll get the array[1,2,3].If have an iterator method, which does not do this (from some library perhaps, which does not adhere to this convention), you can use
foo.enum_for(:bar)to get an enumerable which contains all the values yielded bybar.So hypothetically, if
get_historical_quotes_daysdid not already return an array, you could useYahooFinance.enum_for(:get_historical_quotes_days).map {|row| row.join(",") }to get what you want.