LoginSignup
0
0

More than 1 year has passed since last update.

to_iメソッドの使い方

Last updated at Posted at 2021-08-27

to_iとは?

数字の文字列を数値オブジェクトに変換するメソッドです。
また、小数を整数に変換することもできます。

以下、サンプルコードになります。

使用例
オブジェクト.to_i

num = "1"
p num
=> "1" (文字列)

num.to_i
=> 1 (整数)

puts 100 + "100"  #数値オブジェクト + 文字オブジェクトは計算できない
puts 100 + "100".to_i #to_iを使って文字オブジェクト ⇒ 数値オブジェクトに変える
⇒ 200

小数を整数に変えることもできる

# 小数として定義
num = 1.0
num.class
=> Float

#整数に変換
num = num.to_i
num.class
=> Integer

参考記事

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