1

Within my seed.rb I'm populating 4 columns with text data from one title-1.txt file.

title  = File.read(File.join(Rails.root, '/features/support/titles/title-1.txt'))  

1.upto(4) do |i|
  PressRelease.create(
    :title => title
  )
end

I want to populate each column with different content from different txt files (title-1.txt, title-2.txt, ...)

I know I can make this:

1.upto(4) do |i|
  PressRelease.create(
    :title => File.read(File.join(Rails.root, '/features/support/titles/title-' + "#{i}" +'.txt'))
  )
end  

To make it short I've tried changing the title variable into this:
(notice the title-"#{i}")

title  = File.read(File.join(Rails.root, '/features/support/titles/title-' + "#{i}" + '.txt'))

But I get this error:
Undefined local variable or method `i' for main:Object

Any tip how to make a reusable and short variable that let's me use it in iterations?

-- UPDATE --
This post doesn't have a complete solution, from the answer of @Paul Fioravanti I got an alternate method to shorten the code. The url must be stored in the variable without the File.open methods, like this:

title_url  = '/features/support/titles/title-' + '%s' + '.txt'  

1.upto(4) do |i|
  PressRelease.create(
    :title => File.read(File.join(Rails.root, "#{title_url %i}"))
  )
end

1 Answer 1

1

How about this solution I got from this StackOverflow thread, so you can keep the variable short inside your loop, and don't need to define the numbered file when you define the title variable:

title  = File.read(File.join(Rails.root, '/features/support/titles/title-' + '%s' + '.txt'))
1.upto(4) do |i|
  PressRelease.create(
    :title => title % i
  )
end
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I get this message: No such file or directory - /directories/title-%s.txt. But your method works when I store the url in a variable without the File functions. So in the create method I have this| :title => File.read(File.join(Rails.root, "#{title_url %i}")), I'll wait some time, if there is not a better answer I'll set yours as accepted.
Nice catch...should have known that. If you end up choosing this solution, please edit your question to post the final answer so that others don't need to accidentally use non-tested code in their solutions :-)

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.