Tag: class method

类方法(ruby)

这里有新手,很难理解类方法以及为什么我无法在实例中正确显示属性。 class Animal attr_accessor :noise, :color, :legs, :arms def self.create_with_attributes(noise, color) animal = self.new(noise) @noise = noise @color = color return animal end def initialize(noise, legs=4, arms=0) @noise = noise @legs = legs @arms = arms puts “—-A new animal has been instantiated.—-” end end animal1 = Animal.new(“Moo!”, 4, 0) puts animal1.noise animal1.color = “black” […]

有没有办法从Ruby中的实例调用私有Class方法?

除了self.class.send :method, args…当然。 我想在类和实例级别提供一个相当复杂的方法,而不需要复制代码。 更新: @Jonathan Branam:这是我的假设,但我想确保没有其他人找到方法。 Ruby中的可见性与Java中的可见性非常不同。 你也很正确, private不能在类方法上工作,尽管这会声明一个私有类方法: class Foo class < NoMethodError: private method ‘bar’ called for Foo:Class