Agathe
Agathe

Reputation: 313

Create an array from each line of a file in Ruby Rake

I would like to create an array in Ruby rake called ARRAY where each line of an infile ("infile.txt") is an element of the array. This is how I have tried it so far:

desc "Create new array"
task :new_array do
ARRAY=Array.new
end

desc "Add elements to array"
task :add_elements => [:new_array] do
File.open("infile.txt").each do |line|
ARRAY.push(#{line})
end
end

However, I get the following error:

syntax error, unexpected keyword_end, expecting ')'

for the end after "ARRAY.push(#{line})"

Can someone explain to me what the problem is or let me know of another way to do this?

Many thanks!

Upvotes: 1

Views: 1191

Answers (2)

mu is too short
mu is too short

Reputation: 434975

Your problem is that you're trying to use string interpolation (#{...}) outside a string:

ARRAY.push(#{line})
# ---------^^^^^^^

You could use string interpolation by throwing in some double quotes:

ARRAY.push("#{line}")

but there's no need to convert a string (line) to an identical string ("#{line}") so you could just push straight onto the array:

ARRAY.push(line)

Or you could just skip all that explicit iteration and use #to_a:

array = File.open("infile.txt").to_a

And if you wanted to strip off the newlines:

array = File.open('infile.txt').map(&:chomp)

As engineersmnky points out in the comments, using File.readlines would be a better approach:

array = File.readlines('infile.txt')
array = File.readlines('infile.txt').map(&:chomp)
#...

And don't forget to check IO as well as File for methods when working with files.

Upvotes: 1

lucaortis
lucaortis

Reputation: 430

You can also do this:

array = []

IO.foreach("path/to/file.txt") { |line|

  array.push(line.chomp)

} 

Then if you want to clear the array from empty lines just use delete:

array.delete("")

Upvotes: 0

Related Questions