From: Julian Leviston Date: 2009-02-05T09:35:33+09:00 Subject: Re: Making object methods available externally Put "self." in front of the method name in it's definition. This is called a class method. If you need both, have both. Blog: http://random8.zenunit.com/ Learn rails: http://sensei.zenunit.com/ On 05/02/2009, at 5:37 AM, David Stanford wrote: > 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 # @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 > -- > Posted via http://www.ruby-forum.com/. >