code - Ruby 菜鸟代码拍砖
大家讲道理
大家讲道理 2017-04-24 09:10:48
0
1
586

公司最近组织了一个技能鉴定,试题如下:
有一个采用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代码。

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(1)
Peter_Zhu

Let me throw some light...

  • Coding style

    • Double space indent

    • Brackets for function calls with parameters File.exists?(file)

    • Optional function parameters encoding:'GBK'

    • Function parameters are separated by ,

  • Exception handling

    • Exception handling in the original code has no meaning, it is better to raise the error directly

  • Function usage

    • String#gsub

    • File.expand_path

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,})/, '')

  # 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])

As for optimization, if "HelloHelloHello" is repeated three times in a row, you will be dumbfounded~

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!