Chaining in rails (ERB) files

125 views Asked by At

What is rubys (ERB) equivalent of the following PHP code?

<?php echo $first_variable . " " . $second_variable ?>
3

There are 3 answers

2
sansarp On BEST ANSWER

You can do it like this:
<%= first_variable_value + " " + second_variable_value %>

However, if variables store Fixnum instead of String then the following error occurs
TypeError: String can't be coerced into Fixnum.

Therefore the best approach would be
<%= "#{first_variable} #{last_variable}" %>

Interpolation implecitly converts the Fixnum into String and problem solved.

0
twonegatives On
<%= "#{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

2
Arslan Ali On

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}" %>