1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Ruby] to_iメソッドで基数(進数)を指定する

Posted at

はじめに

Rubyシルバーの勉強をしている中でto_iメソッドを用いて基数を指定する部分があったのでまとめていきます。

to_iメソッドで基数を指定する

to_iメソッドは、文字列を整数に変換するメソッドです。
引数を指定しない場合は10進数として解釈されますが、基数(進数)を指定することで2進数や16進数などとして解釈し、整数に変換することができます。

# 何も指定しないと10進数として解釈される
"12".to_i # => 12

# 基数(2)を指定すると2進数として解釈される
"10111".to_i(2) # => 23

# 基数(8)を指定すると8進数として解釈される
"070".to_i(8) # => 56

# 基数(16)を指定すると16進数として解釈される
"A61".to_i(16) # => 2657

まとめ

今回はto_iメソッドにおける基数の指定方法について解説しました。
進数を適切に指定することで、さまざまな表現の文字列を整数に変換することができます。
最後まで読んでいただきありがとうございました。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?