首页 > Ruby 菜鸟代码拍砖

Ruby 菜鸟代码拍砖

公司最近组织了一个技能鉴定,试题如下:
有一个采用CP936编码(也称为GBK)的文本文件,名字为a.txt,该文件中存在一些连续重复的内容,比如“HelloHello”,“国庆60周年国庆60周年”,这是因为作者在编辑的时候不小心而导致的错误,现在要求你编写一个程序来自动更正它,并且为了满足国际化的要求,必须使用小端模式的UTF-16编码来另存为新文件(b.txt),具体的去重规则是:

程序对该文件进行分析处理,将上面提到的连续重复两次的内容删除掉重复部分,只保留原始内容。其它不涉及重复的部分保持原样不变。并且,只有被重复的字符串超过3个字符(注意是字符,不是字节)的时候,才算重复,小于或等于3个字符的则不需要处理

require 'pathname'
def magic_change(file)      
    begin   
        #read file      
        return unless File.exists? file
        original_string = IO.read(file,:encoding=>'GBK').encode!('UTF-8')
        #deduplicate characters     
        original_string =original_string.gsub(/([\S]{4,})\1/){Regexp.last_match[1]}
        #write file
        File.open(Pathname.new(File.join(__dir__,'b.txt')).cleanpath,"w:UTF-16LE") do |file|
            file.write original_string
        end
    rescue =>error
        p error
    end
end

magic_change(ARGV[0])

本题解法中的正则应该是没有问题的的,社区大神们看下对代码中的ruby规范,优化,异常处理,常见函数用法等方面有没有更好的建议或者问题,最终目标是写一份正统优秀的ruby代码。


我来抛砖引玉一下...

require 'pathname'
def magic_change(file)      
  # read file      
  return unless File.exists?(file)
  original_string = IO.read(file, encoding:'GBK').encode!('UTF-8')

  # deduplicate characters
  modified_string = original_string.gsub(/([\S]{4,})\1/, '\1')

  # write file
  File.open(File.expand_path(__dir__, 'b.txt'), "w:UTF-16LE") do |file|
    file.write modified_string
  end
end

magic_change(ARGV[0])

至于优化嘛,如果是连续三个重复 "HelloHelloHello",就傻眼了~

【热门文章】
【热门文章】