Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String concatenation vs. interpolation in Ruby

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 Pine's "Learn to Program" taught me to write a basic program like this...

num_cars_again= 2 puts 'I own ' + num_cars_again.to_s + ' cars.' 

This is fine, but then I stumbled across the tutorial on ruby.learncodethehardway.com, and was taught to write the same exact program like this...

num_cars= 2 puts "I own #{num_cars} cars." 

They both output the same thing, but obviously option 2 is a much shorter way to do it.

Is there any particular reason why I should use one format over the other?

like image 405
Jeff H. Avatar asked Apr 09 '12 16:04

Jeff H.


People also ask

What's the difference between concatenation and interpolation Ruby?

Concatenation allows you to combine to strings together and it only works on two strings. Swift uses string interpolation to include the name of a constant or variable as a placeholder in a longer string, and to prompt Swift to replace it with the current value of that constant or variable.

What is the difference between string concatenation and interpolation?

You can think of string concatenation as gluing strings together. And, you can think of string interpolation without strings as injecting strings inside of other strings.

What is string interpolation in Ruby?

String Interpolation, it is all about combining strings together, but not by using the + operator. String Interpolation works only when we use double quotes (“”) for the string formation. String Interpolation provides an easy way to process String literals.

What is string concatenation in Ruby?

concat is a String class method in Ruby which is used to Concatenates two objects of String. If the given object is an Integer, then it is considered a codepoint and converted to a character before concatenation. Syntax:String_Object.concat(String_Object)


1 Answers

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)
like image 106
Phrogz Avatar answered Oct 07 '22 21:10

Phrogz