How to print an array

Hi, I have done this method in order to put the content of a txt file
into an array. Now I should have to construct a bucle out of the method
to print the content of the array in the screen but I dont’t know what
to do. This is my method:

def cargar_tokens(txtFileName)
tokens=[]
txtFile = File.open(txtFileName)
txtFile.each(" ") do |palabra|
if (palabra=~ /(.+)/)
token = $1
tokens.push(token)
end
end
txtFile.close
return tokens
end

if (ARGV.length<1)
puts “I need one argument: 1) name of the file”
else
tokens=cargar_tokens(ARGV[0])
end

Not sure what a “bucle” is :slight_smile:

Here are some options to try:

puts tokens.join(", ")

puts tokens.inspect

tokens.each do |token|
puts token
end

On Wed, Aug 11, 2010 at 5:01 PM, Brian C. [email protected]
wrote:

Not sure what a “bucle” is :slight_smile:

It’s a loop.

Jesus.

Francisco M. wrote:

def cargar_tokens(txtFileName)
tokens=[]
txtFile = File.open(txtFileName)
txtFile.each(" ") do |palabra|
if (palabra=~ /(.+)/)
token = $1
tokens.push(token)
end
end
txtFile.close
return tokens
end

if (ARGV.length<1)
puts “I need one argument: 1) name of the file”
else
tokens=cargar_tokens(ARGV[0])
end

It looks like Brian answered your question, but if you are interested in
the more idiomatic “ruby” approach you can do something more like:

def cargar_tokens(txt_file_name)
tokens = []
File.open(txt_file_name) do |file|
file.each_line(’ ') { |palabra| tokens << $1 if palabra =~ /(.+)/ }
end

tokens
end

if ARGV.empty?
puts “I need one argument: 1) name of the file”
else
tokens = cargar_tokens(ARGV.first)
end

The nice rubyisms are what make it fun, to me at least!

Hi –

On Thu, 12 Aug 2010, Brian C. wrote:

end
Also:

puts tokens

David


David A. Black, Senior Developer, Cyrus Innovation Inc.

The Ruby training with Black/Brown/McAnally
Compleat Philadelphia, PA, October 1-2, 2010
Rubyist http://www.compleatrubyist.com