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
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论