6
6

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.

Rubyの整数から下1桁や2桁取る方法

Last updated at Posted at 2019-07-08

#コード


x = 123456789
puts x % 10
puts x % 100
puts x % 1000
puts x % 10000

出力結果↓

9
89
789
6789

あまりで下1桁、や2桁を取ってます。
ただ、ピンポイントでほしい桁だけを取ることが出来ません。

ピンポイントでほしい桁だけを取るときは


x = 123456789
puts x.to_s.split("")[-1]
puts x.to_s.split("")[-2]
puts x.to_s.split("")[-3]
puts x.to_s.split("")[-4]

出力結果↓

9
8
7
6

#訂正しました
もっと簡単に取れる方法を教えて頂いたので、訂正します。
ttakuru88さんありがとうございました。

x = 123456789
p x.digits

出力結果↓

[9, 8, 7, 6, 5, 4, 3, 2, 1]
6
6
6

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
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?