I tried to create a class with a private class method. I want this private class method to be available for use inside the instance method.
The following was my first attempt:
class Animal
class << self
def public_class_greeter(name)
private_class_greeter(name)
end
private
def private_class_greeter(name)
puts "#{name} greets private class method"
end
end
def public_instance_greeter(name)
self.class.private_class_greeter(name)
end
end
Animal.public_class_greeter('John')working fine, print John greets private class method.
However, Animal.new.public_instance_greeter("John")an error: NoMethodError: private method 'private_class_greeter' called for Animal:Class.
It is expected that the call self.class.private_class_greeterwill be the same as Animal.private_class_greeterthat, clearly causing an error.
After finding how to fix this, I came up with the following code that does the job:
class Animal
class << self
def public_class_greeter(name)
private_class_greeter(name)
end
private
def private_class_greeter(name)
puts "#{name} greets private class method"
end
end
define_method :public_instance_greeter, &method(:private_class_greeter)
end
I do not quite understand what is happening here: &method(:private_class_greeter).
Could you explain what this means?
If I had to replace:
define_method :public_instance_greeter, &method(:private_class_greeter)
with:
def public_instance_greeter
XYZ
end
then what should be the content instead XYZ?