Same name for class and instance method

Newbie here.

Consider the following two "say" methods.

irb(main):020:0> class Test2
irb(main):021:1> def self.say(block)
irb(main):022:2> block.call(self.class)
irb(main):023:2> end
irb(main):024:1> def say(block)
irb(main):025:2> block.call(self.class)
irb(main):026:2> end
irb(main):027:1> end
=> nil
irb(main):028:0> Test2.new.say(c)
Test2
=> nil
irb(main):029:0> Test2.say(c)
Class

(1) Do I have the nomenclature correct? Are the two "say" methods a class
and instance method?

(2) Is this valid Ruby both stylistically and semantically?

Newbie here.

Consider the following two "say" methods.

irb(main):020:0> class Test2
irb(main):021:1> def self.say(block)
irb(main):022:2> block.call(self.class)
irb(main):023:2> end
irb(main):024:1> def say(block)
irb(main):025:2> block.call(self.class)
irb(main):026:2> end
irb(main):027:1> end
=> nil
irb(main):028:0> Test2.new.say(c)
Test2
=> nil
irb(main):029:0> Test2.say(c)
Class

(1) Do I have the nomenclature correct? Are the two "say" methods a class
and instance method?

Yes.

(2) Is this valid Ruby both stylistically and semantically?

First of all, using the same name for a class and instance method can cause confusion, so it's probably not a too good idea in the general case. That doesn't mean that there aren't valid use cases for this though.

The way you seem to be using a block (definition of c is missing in your example) is a bit unusual. Usually you would do

def say
   yield self.class
end

or

def say(&block)
   block.call self.class
   # or shorter: block[self.class]
end

And invoke it like

Test2.say do |x|
   puts x
end

Again, it may make sense to invoke the method the way you did but the far more common idiom is the one I have shown.

Kind regards

  robert

ยทยทยท

On 22.11.2009 08:20, Ralph Shnelvar wrote:

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/