Concatenating String with Number in Ruby

Concatenating string with number in 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.

String concatenation in Ruby

You can do that in several ways:

  1. As you shown with << but that is not the usual way
  2. With string interpolation

    source = "#{ROOT_DIR}/#{project}/App.config"
  3. with +

    source = "#{ROOT_DIR}/" + project + "/App.config"

The second method seems to be more efficient in term of memory/speed from what I've seen (not measured though). All three methods will throw an uninitialized constant error when ROOT_DIR is nil.

When dealing with pathnames, you may want to use File.join to avoid messing up with pathname separator.

In the end, it is a matter of taste.

Rails = concatenate integer and string inside model

You can do it by different ways:

string = "#{number}%" # or number.to_s + "%"
=> "50%"

Or by using number_to_percentage Rails helper:

string = number_to_percentage(number)

How to concatenate integer to string in ERB?

to_s is the method you're looking for:

<% item_id = "item" + item_counter.to_s %>

You can also use string interpolation:

<% item_id = "item#{item_counter}" %>

How do I concatenate a string in a while loop?

You can do it in two ways this way:

d = ""
while s = gets do
d << s
end
puts d

Edit: Marc-André Lafortune noticed using += is not very good idea, so I leave only << method here.

Simple string concatenation in rails in view page

in view

<%
var1 = "ruby"
var2 = "on"
var3 = var1 + var2
%>

Finally

<% f_var = "Ruby #{var3}"%>

but this type of code is not recommended in view as it does not look good. You should use helper method for this type of requirement

Why do two strings separated by space concatenate in Ruby?

Implementation details can be found in parse.y file in Ruby source code. Specifically, here.

A Ruby string is either a tCHAR (e.g. ?q), a string1 (e.g. "q", 'q', or %q{q}), or a recursive definition of the concatenation of string1 and string itself, which results in string expressions like "foo" "bar", 'foo' "bar" or ?f "oo" 'bar' being concatenated.



Related Topics



Leave a reply



Submit