3

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                                                                                                              

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Okay, that was easier than I thought. When I comment the block out, create a new object called 'a' and then call 'a.yahoo_data' I get an array. And by assigning a variable such as 'q = a.yahoo_data', the call of q.class returns 'Array'. q.length returns '8'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.