0

I have a text file of stock symbols, each symbol is on its own line. In Ruby, I have created an array from the text file like so:

symbols = []
File.read('symbols.txt').each_line do |line|
  symbols << line.chop!
end

For each symbol in the array, I want to read from a json file (ex. MSFT.json) and perform a number of calculations (all of that is now working) and then do the same thing for the next symbol in the array.

When attempting to "call" and perform calculations on the first item in the array I did this:

json = File.read("#{symbols[0]}.json")
#...calculations come after this

This worked fine, and it did run through the whole program for the first symbol, but of course doesn't go on to perform the same steps for the remaining symbols (I know thats because I specified an index in the array].

Now that I know that the program works for a single symbol, I now want it to run on all the symbols in the array...so after the first block, I tried adding: symbols.each do, and removed the [0] from the File.read line (and added end at the end of the calculations). I was hoping it would loop through everything between the "do" and "end" for each symbol. That didn't work.

Then I tried adding this after the first block:

def page(symbols, i)
  page[i]
end

And changing the File.read line to: json = File.read("#{page[i]}.json)

But that didn't work either.

Any help is appreciated. Thanks a lot

2 Answers 2

1

You can simply use .each instead of an iterator index:

symbols.each do |symbol|
  json = File.read("#{symbol}.json")
  # do some calculation for symbol
end
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot Pinny! It's running now (not complete yet)...but no errors. I'll mark this as correct when it finishes. So the thing I was missing in one of my earlier attempts was the |symbol| part - would you mind explaining what that part means? And thanks again!
The |symbol| part represents the argument list (in this case just one argument 'symbol') for the block that you are passing to each. Here's a simple primer that explains this a bit further - ruby-doc.org/docs/ProgrammingRuby/html/tut_containers.html
0

No need to iterate twice:

open('symbols.txt').lines.each do |line|
  symbol = line.strip
  json = File.read("#{symbol}.json")
  # process json
end

Comments

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.