# Problem with String.my\_custom\_func! "Can't change the value

**URL:** <https://www.ruby-forum.com/t/problem-with-string-my-custom-func-cant-change-the-value/58483>\
**Category:** Ruby\
**Created:** [April 22, 2006, 1:14am UTC](https://www.ruby-forum.com/t/problem-with-string-my-custom-func-cant-change-the-value/58483 "2006-04-22T01:14:38Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![phallstrom](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/f475e1/32.png) [@phallstrom](https://www.ruby-forum.com/u/phallstrom)\
**Post date:** [April 22, 2006, 1:14am UTC](https://www.ruby-forum.com/t/problem-with-string-my-custom-func-cant-change-the-value/58483/1 "2006-04-22T01:14:38Z")

</div>

Hi all -

I’m extending the String class to include a tidy\_up\_html() method that  
runs the string using tidy. Works great. However, I’d like to also  
have a tidy\_up\_html!() method and do it in place.

The problem is that the tidy library _has_ to return a new value, so at  
some point I have to do:

```
self = ......

```

at which point I get the error: Can’t change the value of self

Here’s a trivial example:

class String  
def my\_func!  
self.gsub!(/x/, ‘y’) #okay  
self = result\_of\_tidy\_call #not okay  
end  
end

I’m new enough to ruby that I can’t figure out how to work around  
this…

Suggestions?

Thanks!

-philip

---

<div class="post-metadata">

**Author:** ![phallstrom](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/f475e1/32.png) [@phallstrom](https://www.ruby-forum.com/u/phallstrom)\
**Post date:** [April 22, 2006, 1:14am UTC](https://www.ruby-forum.com/t/problem-with-string-my-custom-func-cant-change-the-value/58483/2 "2006-04-22T01:14:44Z")

</div>

Hi –

On Sat, 22 Apr 2006, Philip H. wrote:

> I’m new enough to ruby that I can’t figure out how to work around this…
> 
> Suggestions?

There’s a String#replace method:

s = “abc”  
s.replace(“def”)

s is now the same object, but with different contents.

David

–  
David A. Black (removed\_email\_address@domain.invalid)  
Ruby Power and Light, LLC ([http://www.rubypowerandlight.com](http://www.rubypowerandlight.com))

“Ruby for Rails” PDF now on sale! [Ruby for Rails](http://www.manning.com/black)  
Paper version coming in early May!
