Milktrader
Milktrader

Reputation: 9858

How does one populate an array in Ruby?

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                                                                                                              

Upvotes: 3

Views: 677

Answers (1)

sepp2k
sepp2k

Reputation: 370455

If you don't give a block to get_historical_quotes_days, you'll get an array back. You can then use map on that to get an array of the results of join.

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 then enum = foo.bar will return an enumerable containing the values 1,2,3. And if you do arr = 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 by bar.

So hypothetically, if get_historical_quotes_days did not already return an array, you could use YahooFinance.enum_for(:get_historical_quotes_days).map {|row| row.join(",") } to get what you want.

Upvotes: 4

Related Questions