简体   繁体   中英

Manipulating Variables in HTML-Embedded Ruby

I'm using embedded Ruby in HTML and am trying to create a new variable; however, this seems to be modifying the HTML formatting over the code even though I am just trying to create a new variable and modify it. It seems like when I manipulate newfood, I am also changing the value stored in "food" (almost in a pass-by-reference way). How can I pass it by value (if possible)?

<% newfood = food%>

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

You can use the clone or dup functions for this.

In your case where food is a string, they will both work.

newfood = food.dup
newfood = food.clone

The functions work a bit different, this is what ruby-doc says:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM