Reputation: 173
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
Reputation: 19248
I think the sequence of your code is a little bit wrong.
You should instead;
this
functionExample:
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
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