D
David Stanford
Hi all,
I'm having trouble figuring out a way of creating a method within a
class that's available not only to the other object methods (object
instances), but also externally, as if I were to use 'self.method'.
Below is an (admittedly, lame) example of what I'm referring to:
#############################
class CheesePhrase
def initialize(phrase)
@phrase = phrase
say_it
end
def say_it(phrase=@phrase)
puts "#{phrase}"
end
end
#############################
The above code works fine if I create an object instance, and (if I
choose to do so) call the method 'say_it', like so:
some_cheese_phrase = CheesePhrase.new("I like cheese.")
some_cheese_phrase.say_it
However, what if I'd also like to call the method directly, without
creating a new instance? For example, simply with:
CheesePhrase.say_it("I like cheese, too.")
I can't do this without using 'self.say_it' in the method declaration.
Though, if I do that, I am no longer able to call the method in
'initialize' since 'self.say_it' is now a class method. I get the
following error:
NoMethodError: undefined method `say_it' for #<CheesePhrase:0x284372f4
@phrase="I like cheese">
from (irb):4:in `initialize'
from (irb):11:in `new'
I'm sure I must be doing something wrong, or my concept of how to
implement this is totally wrong. The only other thought I've had is to
create duplicate methods, but this seems to violate the famed DRY
principle. Any advice would be much appreciated.
Thanks in advance!
-David
I'm having trouble figuring out a way of creating a method within a
class that's available not only to the other object methods (object
instances), but also externally, as if I were to use 'self.method'.
Below is an (admittedly, lame) example of what I'm referring to:
#############################
class CheesePhrase
def initialize(phrase)
@phrase = phrase
say_it
end
def say_it(phrase=@phrase)
puts "#{phrase}"
end
end
#############################
The above code works fine if I create an object instance, and (if I
choose to do so) call the method 'say_it', like so:
some_cheese_phrase = CheesePhrase.new("I like cheese.")
some_cheese_phrase.say_it
However, what if I'd also like to call the method directly, without
creating a new instance? For example, simply with:
CheesePhrase.say_it("I like cheese, too.")
I can't do this without using 'self.say_it' in the method declaration.
Though, if I do that, I am no longer able to call the method in
'initialize' since 'self.say_it' is now a class method. I get the
following error:
NoMethodError: undefined method `say_it' for #<CheesePhrase:0x284372f4
@phrase="I like cheese">
from (irb):4:in `initialize'
from (irb):11:in `new'
I'm sure I must be doing something wrong, or my concept of how to
implement this is totally wrong. The only other thought I've had is to
create duplicate methods, but this seems to violate the famed DRY
principle. Any advice would be much appreciated.
Thanks in advance!
-David