Hi,
I’m trying to write a small ruby script which accepts:
Input : File or $stdin
Output : File or $stdout
This is my stupid code: #---------------------------------------------------------
def do_some_thing(str)
do some things over str
end
f_in = ARGV[0]
f_out = ARGV[1]
if f_out==nil
fout = File.open(f_out,“w”)
end
if f_in==nil
$stdin.each { |line|
if f_out==nil
print do_some_thing(line)
else
fout.print do_some_thing(line)
end
}
else
File.open(f_in,“r”).each {|line|
if f_out==nil
print do_some_thing(line)
else
fout.print do_some_thing(line)
end
}
end
fout.close if f_out!=nil #--------------------------------------------------------------------
Don’t laugh at me I’m learning Ruby so I would like to hear from
you a better way to write this small code.
I’m trying to write a small ruby script which accepts:
Input : File or $stdin
Output : File or $stdout
Abstraction is the keyword. Put the decision to open a file or
stdin or stdout in a a method on the class File and put that
code in a library. That keeps your application clean and
simple.
class File
def self.open_std(file, mode=“r”, *rest, &block)
if file.nil?
if block_given?
block.call(mode.include?(“r”) ? $stdin : $stdout)
else
mode.include?(“r”) ? $stdin : $stdout
end
else
File.open(file, mode, *rest, &block)
end
end
end
APPLICATION
require “your_library”
def do_some_thing(str)
do some things over str
str.upcase
end
File.open_std(ARGV.shift, “r”) do |f_in|
File.open_std(ARGV.shift, “w”) do |f_out|
f_in.each do |line|
f_out.puts do_some_thing(line)
end
end
end
Hi,
I’m trying to write a small ruby script which accepts:
Input : File or $stdin
Output : File or $stdout
This is my stupid code: #---------------------------------------------------------
def do_some_thing(str)
do some things over str
end
f_in = ARGV[0]
f_out = ARGV[1]
if f_out==nil
fout = File.open(f_out,“w”)
end
if f_in==nil
$stdin.each { |line|
if f_out==nil
print do_some_thing(line)
else
fout.print do_some_thing(line)
end
}
else
File.open(f_in,“r”).each {|line|
if f_out==nil
print do_some_thing(line)
else
fout.print do_some_thing(line)
end
}
end
fout.close if f_out!=nil
fin = ARGV[0] ? File.open(ARGV[0],‘r’) : $stdin
fout = ARGV[1] ? File.open(ARGV[1], ‘w’) : $stdin
fin.each_line do |line|
fout.print do_some_thing(line)
end
Or (hides File.open errors):
fin = File.open(ARGV[0],‘r’) rescue $stdin
fout = File.open(ARGV[1], ‘w’) rescue $stdout
fin.each_line do |line|
fout.print do_some_thing(line)
end
I’m trying to write a small ruby script which accepts:
Input : File or $stdin
Output : File or $stdout
Abstraction is the keyword. Put the decision to open a file or
stdin or stdout in a a method on the class File and put that
code in a library. That keeps your application clean and
simple.
I do not think that tinkering with the core classes is a good idea for
problems as simple as this.