Help us understand the problem. What is going on with this article?

[Ruby]to_iメソッドとto_sメソッドについて

More than 1 year has passed since last update.

to_i と to_s が覚えられない

と言うか覚える気が無いようなのでメモっとく

  • to_iメソッドが文字→数値
  • to_sメソッドが数値→文字

to_iの例

number = "10"
puts number + 90       #エラーになる
puts number.to_i + 90  #OK

to_sの例

number = 10
puts number + "個のりんご"      #エラーになる
puts number.to_s + "個のりんご" #OK

参考文献

ruby 数値と文字列を連結させる方法「to_s」「to_i」メソッド

taro31
RubyとRuby on Rails絶賛勉強中!
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away