"#{}"符号与erb表示法

saw*_*awa 4 ruby string templates eval erb

符号之间有什么区别:

"
  some text
  #{some_ruby_code}
  some text
  #{some_more_ruby_code}
  some_other_text
"
Run Code Online (Sandbox Code Playgroud)

ERB.new("
  some text
  <%=some_ruby_code%>
  some text
  <%=some_more_ruby_code%>
  some_other_text
").result
Run Code Online (Sandbox Code Playgroud)

我只是有一个广泛的印象,即erb符号可能更强大,但不是那么清楚.你能从不同方面比较它们,并告诉哪些应该在什么样的场合使用?什么样的事情可以用一种符号而不是另一种符号来完成?

增加1

到目前为止,大多数答案似乎都声称erb效率低,并且在使用时不"#{ }"应该使用.现在,让我们问另一种方式.为什么"#{ }"符号不能代替erb?它不会更快更好吗?

增加2

下面的大多数答案似乎都假设单个出现"#{ }"不会跨越多行,因此像一个采用多行的循环的代码块不能嵌入其中.但为什么不呢?如果你这样做,我认为没有任何区别<% >,除了在后者你放入<% >每一行.

Jon*_*ing 5

你是对的,你的ERB版本应该产生与正常版本相同的结果(我认为),但它的目的完全不同.

ERB实际上只是为了模板化:如果你需要生成文本(比如HTML页面或文档),一些模板引擎就像ERB是正确的工具.然而,它不适用于简单的字符串插值:虽然它确实能够做到这一点,但它是一种相当周边的方式来实现它.实际上,您实际上是ERB从字符串创建对象,然后将其评估回​​字符串.

您可以通过快速基准了解这是多么低效:

$ irb -rbenchmark -rerb
ruby-1.9.2-p136 :023 > Benchmark.bm do |bm|
ruby-1.9.2-p136 :024 >     bm.report 'interpolation' do
ruby-1.9.2-p136 :025 >       a = 'hello there'
ruby-1.9.2-p136 :026?>     5000.times { "well #{a}" }
ruby-1.9.2-p136 :027?>     end
ruby-1.9.2-p136 :028?>   bm.report 'erb' do
ruby-1.9.2-p136 :029 >       a = 'hello there'
ruby-1.9.2-p136 :030?>     5000.times { ERB.new("well <%= a %>").result(binding) }
ruby-1.9.2-p136 :031?>     end
ruby-1.9.2-p136 :032?>   end
      user     system      total        real
interpolation  0.000000   0.000000   0.000000 (  0.001495)
erb  0.340000   0.000000   0.340000 (  0.352098)
 => true 
Run Code Online (Sandbox Code Playgroud)

将Ruby代码插入字符串的标准方法是#{}在字符串文字中使用.这是在语言级别(而不是在图书馆级别)内置的.