Concatenating string with number in ruby

Ruby

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

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.

Solution 2 - Ruby

Stephen Doyle's answer, using a technique known as "String interpolation" is correct and probably the easiest solution, however there is another way. By calling an objects to_s method that object can be converted to a string for printing. So the following will also work.

puts " Total Revenue of East Cost: " + total_revenue_of_east_cost.to_s

Solution 3 - Ruby

For your example, you might want something more specific than the to_s method. After all, to_s on a float will often include more or less precision than you wish to display.

In that case,

puts " Total Revenue of East Coast: #{sprintf('%.02f', total_revenue_of_east_coast)}"

might be better. #{} can handle any bit of ruby code, so you can use sprintf or any other formatting method you'd like.

Solution 4 - Ruby

I like (see Class String % for details):

puts " Total Revenue of East Coast: " + "%.2f" % total_revenue_of_east_coast

Solution 5 - Ruby

Example bucle

(1..100).each do |i| puts "indice #{i} " end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionitsaboutcodeView Question on Stackoverflow
Solution 1 - RubyStephen DoyleView Answer on Stackoverflow
Solution 2 - RubySteve WeetView Answer on Stackoverflow
Solution 3 - RubyedebillView Answer on Stackoverflow
Solution 4 - RubySteve WilhelmView Answer on Stackoverflow
Solution 5 - RubyCARLOS HERNANDEZView Answer on Stackoverflow