0

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')%>

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.