登录

优美的 Ruby

754
  • 楼主
    def id_check_digit(body) # 校验18位身份证号最后一位的算法
      digits = body.chars.map(&:to_i) # 字符串转逐位数组
      weights = 17.downto(1).map { |e| (2**e) % 11 }
      table = %w[1 0 X 9 8 7 6 5 4 3 2]
      digits.zip(weights).map { |d,w| d*w }.sum.then { |s| table[s % 11] }
    end
    

    image.webp

    • 有很多其他语言没有的实用函数,比如 zip,用来做配对的二元组数组
    • 函数式
    • 注意最后的 then,方便函数 chain

    对了又水一贴😋

    收藏支持反对打赏

4 条回复

发表回复