Same name for class and instance method

R

Ralph Shnelvar

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?
 
R

Robert Klemme

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top