开发者

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜