LoginSignup
0
0

More than 5 years have passed since last update.

[ruby]1.to_s +"hoge"と1.to_s + "hoge"の違い。スペースの有無が問題になる理由

Posted at

伝えたいこと

特に理由がない限り、演算子の前後でスペースは空けようね

経緯

こういう書き方をするとエラーになると聞いた

puts 1.to_s +"hoge"

再現を試みる

$ irb
irb(main):001:0> 1.to_s +"hoge"
TypeError: no implicit conversion of String into Integer
    from (irb):1:in `to_s'
    from (irb):1
    from /usr/local/bin/irb:11:in `<main>'
irb(main):002:0> 1.to_s + "hoge"
=> "1hoge"

確かに。

理由を調べた結果

以下の理由が要因となって、加算という演算子の扱いにならないようです。

可読性もありますが、思わぬバグにつながることもありそうなので、
スペースはちゃんと空けたほうがいいなと思いました :innocent:

0
0
1

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