在 HTML-Embedded Ruby 中操作变量

Manipulating Variables in HTML-Embedded Ruby

我在 HTML 中使用嵌入式 Ruby 并尝试创建一个新变量;但是,这似乎是在修改代码的 HTML 格式,即使我只是想创建一个新变量并对其进行修改。似乎当我操作 newfood 时,我也在更改 "food" 中存储的值(几乎以引用传递的方式)。如何按值传递它(如果可能)?

<% newfood = food%>

<% newfood.gsub!('a','b')%>

您可以为此使用克隆或复制函数。

如果 food 是一个字符串,它们都可以工作。

newfood = food.dup
newfood = food.clone

函数的工作方式有点不同,这就是 ruby-doc 所说的:

In general, clone and dup may have different semantics in descendant classes. While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendant object to create the new instance. http://ruby-doc.org/core-2.4.0/Object.html#method-i-dup-label-on+dup+vs+clone