Jesús Gabriel y Galán
4/23/2009 2:22:00 PM
On Thu, Apr 23, 2009 at 4:01 PM, Keith Salisbury
<keithsalisbury@gmail.com> wrote:
> Or more simply, i would like this to update the variable @greeting, when
> i call Keith.learn_french:
>
> module Keith
> =A0def self.greeting
> =A0 =A0@greeting ||=3D "hello"
> =A0end
> =A0def self.greeting=3D(value)
> =A0 =A0puts "updating knowledge"
> =A0 =A0@greeting =3D value
> =A0end
> =A0def self.speak
> =A0 =A0puts greeting
> =A0end
> =A0def self.learn_french
> =A0 =A0learn_language(greeting, "bonjour")
Here, you are calling the greeting method (which returns "hello")
> =A0end
> =A0def self.learn_language(prop, value)
> =A0 =A0prop =3D value
Here you are reassigning a local variable, which goes out of scope
when the method ends.
Try this:
jesus@jesus-laptop:~/temp/ruby$ ruby class_variables.rb
hello
bonjour
jesus@jesus-laptop:~/temp/ruby$ cat class_variables.rb
module Keith
def self.greeting
@greeting ||=3D "hello"
end
def self.greeting=3D(value)
puts "updating knowledge"
@greeting =3D value
end
def self.speak
puts greeting
end
def self.learn_french
learn_language(:@greeting, "bonjour")
end
def self.learn_language(prop, value)
instance_variable_set(prop, value)
end
end
Keith.speak
Keith.learn_french
Keith.speak
or if you want to call the self.greeting=3D method, try this variation:
def self.learn_french
learn_language(:greeting, "bonjour")
end
def self.learn_language(prop, value)
send("#{prop}=3D", value)
end
Hope this helps,
Jesus.