What is rubys (ERB) equivalent of the following PHP code?
<?php echo $first_variable . " " . $second_variable ?>
What is rubys (ERB) equivalent of the following PHP code?
<?php echo $first_variable . " " . $second_variable ?>
<%= "#{first_variable} #{second_variable}" %>
Note that variables gonna be transformed to string representation (which could produce some unexpected outputs like "Photo:0x0000000dc9f5b0"). More on various ways to concatenate strings here: String concatenation in Ruby
You don't need "
to print a variable; you can do so without "
.
<%= first_variable %>
This is equivalent of following PHP code:
<?php echo $first_variable ?>
So in order to do what you have asked in your question, the following code is suitable:
<%= first_variable + " " + last_variable %>
You don't need to surround your variables with "
. And +
operator here does the job for concatenation.
And in case, if you are not sure that variables are actually string object, the you can use either of the following techniques:
<%= first_variable.to_s + " " + last_variable.to_s %>
<%= "#{first_variable} #{last_variable}" %>
You can do it like this:
<%= first_variable_value + " " + second_variable_value %>
However, if variables store
Fixnum
instead ofString
then the following error occursTypeError: String can't be coerced into Fixnum
.Therefore the best approach would be
<%= "#{first_variable} #{last_variable}" %>
Interpolation implecitly converts the
Fixnum
intoString
and problem solved.