Could someone explain how i get this to work please:
module Keith
def self.greeting @greeting ||= “hello”
end
def self.greeting=(value)
puts “updating knowledge” @greeting = value
end
def self.speak
puts greeting
end
def self.learn_ruby
self.greeting = “ruby”
end
def self.learn_french
learn_language(greeting, “bonjour”)
end
def self.learn_language(prop, value)
puts prop.inspect
prop = value
puts prop.inspect #p =
value
end
end
Or more simply, i would like this to update the variable @greeting, when
i call Keith.learn_french:
module Keith
def self.greeting @greeting ||= “hello”
end
def self.greeting=(value)
puts “updating knowledge” @greeting = value
end
def self.speak
puts greeting
end
def self.learn_french
learn_language(greeting, “bonjour”)
end
def self.learn_language(prop, value)
prop = value
end
end
Keith.speak
Keith.learn_french
Keith.speak
But the only way i can get it to work is using this:
module Keith
def self.greeting @greeting ||= “hello”
end
def self.greeting=(value)
puts “updating knowledge” @greeting = value
end
def self.speak
puts greeting
end
def self.learn_french
self.greeting = learn_language(greeting, “bonjour”)
end
def self.learn_language(prop, value)
prop = value
end
end
Keith.speak
Keith.learn_french
Keith.speak
Which is basically the same as:
module Keith
def self.greeting @greeting ||= “hello”
end
def self.greeting=(value)
puts “updating knowledge” @greeting = value
end
def self.speak
puts greeting
end
def self.learn_french
self.greeting = “bonjour”
end
end
jesus@jesus-laptop:~/temp/ruby$ cat class_variables.rb
module Keith
def self.greeting @greeting ||= “hello”
end
def self.greeting=(value)
puts “updating knowledge” @greeting = 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= method, try this variation:
def self.learn_french
learn_language(:greeting, “bonjour”)
end
def self.learn_language(prop, value)
send(“#{prop}=”, value)
end
It’s worth mentioning that none of the code in this thread contains any
class variables. What you’ve got are instance variables (belonging to a
class object). Class variables look like @@this.
Although I’d think that you’d be better with a Speaker class and do:
Keith = Speaker.new
Then you’d be dealing with instance variables on instances of the
Speaker class rather than instance variables on the Keith module.
Contrary to what you might think, you don’t have class variables in
your code. (Those would be @@greeting)