2022/05/05 今回の気になった bugs.ruby のチケット

今週は Array#undigits の提案がありました。

[Feature #18762] Add an Array#undigits that compliments Integer#digits

class Array
  def undigits(base = 10)
    each_with_index.sum do |digit, exponent|
      digit * base**exponent
    end
  end
end

pp 42.digits
# => [2, 4]

pp 42.digits.undigits
#=> 42

# 16進数で変換
pp 42.digits(16)
# => [10, 2]

pp 42.digits(16).undigits(16)
#=> 42
  • より厳密に提示されている Ruby の実装コード
class Array
  def undigits(base = 10)
    base_int = base.to_int
    raise TypeError, "wrong argument type #{base_int.class} (expected Integer)" unless base_int.is_a?(Integer)
    raise ArgumentError, 'negative radix' if base_int.negative?
    raise ArgumentError, "invalid radix #{base_int}" if base_int < 2

    each_with_index.sum do |digit, exponent|
      raise MathDomainError, 'out of domain' if digit.negative?

      reverse.reduce(0) do |acc, digit|
        acc * base + digit
      end
    end
  end
end
  • あると便利なんですかね