[英]Chaining in rails (ERB) files
以下PHP代码等效于rubys(ERB)?
<?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"). 请注意,变量将转换为字符串表示形式(这可能会产生一些意外的输出,例如“ Photo:0x0000000dc9f5b0”)。 More on various ways to concatenate strings here: String concatenation in Ruby 有关连接字符串的各种方法的更多信息,请参见:Ruby中的字符串连接
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 但是,如果变量存储Fixnum
而不是String
,则将发生以下错误
TypeError: String can't be coerced into Fixnum
. 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. 插值将Fixnum
轻松地转换为String
并解决了问题。
You don't need "
to print a variable; you can do so without "
. 您不需要"
打印变量;您可以不使用"
。
<%= first_variable %>
This is equivalent of following PHP code: 这等效于以下PHP代码:
<?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}" %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.