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)?
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.
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".
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 << .
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}" %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With