# Can't change the value of self

**URL:** <https://www.ruby-forum.com/t/cant-change-the-value-of-self/191627>\
**Category:** Ruby\
**Created:** [July 15, 2010, 3:49pm UTC](https://www.ruby-forum.com/t/cant-change-the-value-of-self/191627 "2010-07-15T15:49:27Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ralphshnelvar](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e19adc/32.png) [@ralphshnelvar](https://www.ruby-forum.com/u/ralphshnelvar)\
**Post date:** [July 15, 2010, 3:49pm UTC](https://www.ruby-forum.com/t/cant-change-the-value-of-self/191627/1 "2010-07-15T15:49:27Z")

</div>

Ok … I’ve googled this error and I see stome explanations about usnig  
destructive methods …

I don’t get it.

Consider

* * *

class UD\_Config  
attr\_accessor :container\_list  
attr\_accessor :screen\_x, :screen\_y, :screen\_width, :screen\_height

@@config\_filename = ‘config.yml’

def initialize  
debugger  
if File.exists? @@config\_filename  
config\_yaml\_str = IO.read(@@config\_filename)  
self = YAML::load( config\_yaml\_str ) # This line seems to be  
the problem  
else  
set\_defaults  
end  
end

def write\_me  
yaml\_obj = YAML::dump( self )  
File.open(filename,“w”) { |f| f \<\< yaml\_obj }  
end

private

# call this if there is no config file

def set\_defaults  
screen\_x, screen\_y, screen\_width, screen\_height = 30, 30, 600, 500

```
@container_list =
  %w(
    c:\abc\def.udd
    d:\def\ghi.udd
    f:\\ghi\jkl.udd
  )

```

end  
end

* * *

I have been taught that “an object should take care of itself” …  
what’s the right way to do what I want?

---

<div class="post-metadata">

**Author:** ![ralphshnelvar](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e19adc/32.png) [@ralphshnelvar](https://www.ruby-forum.com/u/ralphshnelvar)\
**Post date:** [July 15, 2010, 6:39pm UTC](https://www.ruby-forum.com/t/cant-change-the-value-of-self/191627/2 "2010-07-15T18:39:04Z")

</div>

Ralph S. wrote:

> I have been taught that “an object should take care of itself” …

It can take care of itself, it can’t turn into someone else 🙂

If YAML.load is returning an instance of class UD\_Config directly, then  
just return that to the user. Make a class method, so they call

res = UD\_Config.load(…)

instead of

res = UD\_Config.new(…)

Otherwise, YAML.load is returning some other object - possibly a Hash -  
with which you wish to initialize your new UD\_Config object. So you need  
to copy values out of that object into your object’s instance variables.

If YAML.load gives an object with instance variables, you can copy them  
in a loop: look at ‘instance\_variables’ and ‘instance\_variable\_get’ /  
‘instance\_variable\_set’
