On Fri, Feb 6, 2009 at 6:58 AM, Robert Klemme
<shortcutter / googlemail.com> wrote:
> 2009/2/5 David Stanford <dthomas53 / hotmail.com>:
>
>> Judging from everyone's response, it sounds like what I'm trying to do
>> isn't typically done.
>
> Agreed.
>
>> My mindset was, first, to simply create a standard
>> class. While creating one of the object methods for that class, I
>> realized that the same method code would be useful to call directly,
>> without having to create an object instance; so, as I said, I was
>> thinking there must be some way to do this, without repeating the same
>> (or a similar piece) of code somewhere else.
>
> In that case I would have the method definition *only* at class level
> since apparently it is independent of instance state.  I wouldn't even
> have it as instance method at all.  That avoids confusion.  If you
> need to invoke the method from instance methods the
> self.class.a_method() idiom works well IMHO.


I think that depends on why the method is useful at both places; one
thing I've seen occasionally is the use case where it is useful at the
class level because there are lots of times you'd like to create an
instance, call the method, and then be done with the instance, so it
makes sense to have something like:

class Foo
  def initialize(init_arg1, ..., init_argn)
    # setup
  end

  def action(action_arg1, ..., action_argn)
    # do the action
  end

  def self.action(init_arg1, ..., init_argn, action_arg1, ..., action_argn)
    new(init_arg1, ..., init_argn).action(action_arg1, ..., action_argn)
  end
end

If that's the reason, using the CheesePhrase example:

class CheesePhrase
  # all the stuff in the original example
  def self.say_it(phrase)
    new(phrase).say_it
  end
end