Read from stdin or file in single stagment in ruby
I have this code
if filename
begin
if filename == '-'
ARGF.each{|url|
begin
check(url)
rescue Timeout::Error, Errno::ETIMEDOUT
puts "Timeout Error, try again"
redo
end
}
else
File.open(filename) {|file|
file.each{|url|
begin
check(url)
rescue Timeout::Error, Errno::ETIMEDOUT
puts "Timeout Error, try again"
redo
end
}
开发者_运维技巧 }
end
rescue Interrupt, Errno::EINTR
exit(1)
end
end
But I don't want repeated code for stdin and file, how can I rewrite it?
You can pull out your repeated code into a method and call that on ARGF
or file
as they respond to the same methods.
def do_check(to_check)
to_check.each do |url|
begin
check(url)
rescue Timeout::Error, Errno::ETIMEDOUT
puts "Timeout Error, try again"
redo
end
end
end
Then your example becomes:
if filename
begin
if filename == '-'
do_check(ARGF)
else
File.open(filename) do |file|
do_check(file)
end
end
rescue Interrupt, Errno::EINTR
exit(1)
end
end
I've used do ... end
rather than {}
simply because I find it easier to read.
Try using $<
special variable: http://ruby.wikia.com/wiki/Special_variable
精彩评论