如何在 Ruby 中访问私有类方法? [英] How to access private class methods in Ruby?

查看:45
本文介绍了如何在 Ruby 中访问私有类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中给定一个类:

Given a Class in Ruby:

class MyClass
  def self.my_class_method
    puts "class method"
  end

  private

  def my_method
    puts "regular method"
  end

  private_class_method :my_class_method
end

要访问私有方法,我可以在类对象上调用 .send(:my_method),但这对类方法有何作用?

To access private methods I can call .send(:my_method) on the Class Object, but how does that work for class methods?

推荐答案

你应该这样做:

class MyClass
  def self.my_class_method
    puts "class method"
  end

  private

  def my_method
    puts "regular method"
  end

  private_class_method :my_class_method
end

# to call class method
MyClass.send :my_class_method # => class method
# to call instance method
MyClass.new.send :my_method # => regular method

在 Ruby 中,类也是对象,因此您也可以在类上调用 #send 方法.

In Ruby, class(s) are also objects, so you can call the #send method on the class also.

在 Ruby 中,您可以将私有类方法定义为

In Ruby, you can define private class methods as

class MyClass
  class << self
    private 

    def my_class_method
      puts "class method"
    end
  end
end

或者使用类似的方法:private_class_method

这篇关于如何在 Ruby 中访问私有类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆