What does `&method(:method_ name)` mean in ruby?

Viewed 1312

I was trying to create a class that has a private class method. I want this private class method available to be used inside an 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') works fine, printing John greets private class method.

However, Animal.new.public_instance_greeter("John") throws an error: NoMethodError: private method 'private_class_greeter' called for Animal:Class.

That is expected, as the invocation self.class.private_class_greeter is same as Animal.private_class_greeter, which obviously throws an error.

After searching on how this can be fixed, 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 don't exactly understand what is happening here: &method(:private_class_greeter).

Could you please explain what does this mean?

If I were to replace:

define_method :public_instance_greeter, &method(:private_class_greeter)

with:

def public_instance_greeter
  XYZ
end

then, what should be the content in place of XYZ?

2 Answers
Related