0

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

<?php echo $first_variable . " " . $second_variable ?>
Arslan Ali
  • 17,418
  • 8
  • 58
  • 76
Jakub Kohout
  • 1,854
  • 3
  • 21
  • 36

3 Answers3

3
<%= "#{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

Community
  • 1
  • 1
twonegatives
  • 3,400
  • 19
  • 30
0

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.

Shiva
  • 11,485
  • 2
  • 67
  • 84
sansarp
  • 1,446
  • 11
  • 18
  • That's exactly I was looking for! Thank you :) – Jakub Kohout Jun 07 '15 at 16:36
  • 2
    I think you meant `<%= first_variable_value + " " + second_variable_value %>`. The way you have it, it will just print the words `first_variable_value` and `second_variable_value` – Jim Deville Jun 07 '15 at 16:40
  • in case `first_variable` is a complex object (e.g. Rails model instance), this would end with `undefined method + for Model:0x0000000dd7ef30` – twonegatives Jun 08 '15 at 07:13
0

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}" %>
Arslan Ali
  • 17,418
  • 8
  • 58
  • 76