String concatenation vs. interpolation in Ruby

前端 未结 5 1148
北海茫月
北海茫月 2020-11-27 16:06

I am just starting to learn Ruby (first time programming), and have a basic syntactical question with regards to variables, and various ways of writing code.

Chris

5条回答
  •  长情又很酷
    2020-11-27 16:23

    Whenever TIMTOWTDI (there is more than one way to do it), you should look for the pros and cons. Using "string interpolation" (the second) instead of "string concatenation" (the first):

    Pros:

    • Is less typing
    • Automatically calls to_s for you
    • More idiomatic within the Ruby community
    • Faster to accomplish during runtime

    Cons:

    • Automatically calls to_s for you (maybe you thought you had a string, and the to_s representation is not what you wanted, and hides the fact that it wasn't a string)
    • Requires you to use " to delimit your string instead of ' (perhaps you have a habit of using ', or you previously typed a string using that and only later needed to use string interpolation)

提交回复
热议问题