Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate integer to string in ERB?

If item_counter=213 then I want to set item_id to "item213". Seems easy but:

<% item_id = "item" + item_counter %>

results in an error: can't convert Fixnum into String

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

outputs a strange character: item

   <% item_id = "item#item_counter" %>

is understood as item#item_counter

What is the correct way to concatenate an integer to a string in ERB (Ruby on rails 3)?

like image 837
Nicolas Raoul Avatar asked Jul 07 '11 03:07

Nicolas Raoul


People also ask

How do you combine integers and strings?

To concatenate a string to an int value, use the concatenation operator. Here is our int. int val = 3; Now, to concatenate a string, you need to declare a string and use the + operator.

How do you concatenate strings in Visual Basic?

There are two concatenation operators, + and & . Both carry out the basic concatenation operation, as the following example shows. Dim x As String = "Mic" & "ro" & "soft" Dim y As String = "Mic" + "ro" + "soft" ' The preceding statements set both x and y to "Microsoft".

How do I concatenate a string and a number in Ruby?

Concatenating strings or string concatenation means joining two or more strings together. In Ruby, we can use the plus + operator to do this, or we can use the double less than operator << .


1 Answers

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}" %>
like image 150
Dylan Markow Avatar answered Sep 18 '22 21:09

Dylan Markow