Dlaw
Dlaw

Reputation: 173

How do I output loops to a text file in ruby?

I have searched for this a lot and most articles relating to this are about php and python. However they were not actually answering my question.WHEN I OPEN A TEXT FILE I WANT TO BE ABLE TO SEE THE OUTPUT THERE.I have already tried the method below. The code ran with no errors but it didn't output to the file "filename".

def this()
  i = 0
  until i>=20
    i += 1
    next unless (i%2)==1
    puts i
  end
end 

filename = ARGV
script = $0
that = puts this
txt = File.open(filename,'w')
txt.write(that)
txt.close()*

Upvotes: 1

Views: 1311

Answers (2)

Samuel Toh
Samuel Toh

Reputation: 19248

I think the sequence of your code is a little bit wrong.

You should instead;

  1. Do whatever you want e.g. process ARGV (This step is fine)
  2. Open the file - this returns you the file handler
  3. Pass the file handler to the this function
  4. Write the content
  5. Close the file

Example:

def this(file)
  i = 0
  until i>=20
    i += 1
    next unless (i%2)==1
    file.puts(i)
  end
end 

# Main
begin
  file = File.open('hello.txt','w')
  this(file)
rescue IOError => e
  puts "oops"
ensure 
  file.close()
end

Output:

1
3
5
7
9
11
13
15
17
19

You should also be capturing potential IO errors, this is a fairly common practise.

Upvotes: 1

zetetic
zetetic

Reputation: 47548

def this(file)
  i = 0
  until i>=20
    i += 1
    next unless (i%2)==1
    # Normally 'puts' writes to the standard output stream (STDOUT)
    # which appears on the terminal, but it can also write directly
    # to a file ...
    file.puts i
  end
end

# Get the file name from the command line argument list. Note that ARGV
# is an array, so we need to specify that we want the first element
filename = ARGV[0]

# Open file for writing
File.open(filename, 'w') do |file|
  # call the method, passing in the file object
  this(file)
  # file is automatically closed when block is done
end

Upvotes: 0

Related Questions