Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating string with number in ruby

Tags:

ruby

I am total begineer in ruby so its very novice question.

I am trying to concatenate a string with a float value like follows and then printing it.

puts " Total Revenue of East Cost: " + total_revenue_of_east_cost  

total_revenue_of_east_cost is a variable holding float value, how i can make it print?

like image 996
itsaboutcode Avatar asked Dec 21 '09 13:12

itsaboutcode


People also ask

How do you concatenate a variable and a string in Ruby?

Concatenation looks like this: a = "Nice to meet you" b = ", " c = "do you like blueberries?" a + b + c # "Nice to meet you, do you like blueberries?" You can use the + operator to append a string to another. In this case, a + b + c , creates a new string. Btw, you don't need to use variables to make this work.

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'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.


1 Answers

This isn't exactly concatenation but it will do the job you want to do:

puts " Total Revenue of East Cost: #{total_revenue_of_east_cost}" 

Technically, this is interpolation. The difference is that concatenation adds to the end of a string, where as interpolation evaluates a bit of code and inserts it into the string. In this case, the insertion comes at the end of your string.

Ruby will evaluate anything between braces in a string where the opening brace is preceded by an octothorpe.

like image 110
Stephen Doyle Avatar answered Sep 27 '22 19:09

Stephen Doyle