3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby2.4未満でもInteger#digitsを使いたい!!

Last updated at Posted at 2017-09-19

Ruby2.4に整数を1桁ずつ配列に入れて返すInteger#digitsメソッドが追加されました:tada:
便利なことに基数を指定するとn進数の1桁目,2桁目...を取得できます

12345.digits #=> [5, 4, 3, 2, 1]
4.digits(2)  #=> [0, 0, 1]

詳しくはこっちを見てね
paizaやってたのですがRubyのバージョンが2.3.3でこのメソッドが使えない><
なのでFixnum classをオープンして作っちゃいます

class Fixnum
  def digits(n = 10)
    raise Math::DomainError, 'out of domain' if self < 0
    raise ArgumentError, "invalid radix #{n}" if n < 1 || n > 36
    self.to_s(n).chars.map(&:to_i).reverse
  end
end
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?