ruby – “class << Class”(尖括号)语法的目的是什么?
为什么我要使用类<<添加任何类?类语法?
class Fun def much_fun # some code here end end class << Fun # the difference is here! def much_more_fun # some code here end end 而不是使用猴子修补/鸭子打孔方法: class Fun def much_fun # some code here end end class Fun # the difference is here! def much_more_fun # some code here end end 在阅读Why’s Poignant Guide to Ruby时,我遇到了: 为什么要定义一个类LotteryDraw: class LotteryDraw # some code here def LotteryDraw.buy( customer,*tickets ) # some code here as well end end 并在一段时间后向LotteryDraw类添加一个方法: class << LotteryDraw def play # some code here end end 说:
这种语法的目的是什么?为什么为什么决定这样做而不是使用猴子补丁方法呢? 这些是一些相关的问题和网站: > Adding a new method to the Array class 解决方法
需要更多解释.在ruby中,几乎每个对象都可以创建一个称为实例类的奇怪的东西.这个东西就像一个普通的类,主要区别在于它只有一个实例,并且该实例是在该类之前创建的.
简而言之,有了A级,你可以这样做: a = A.new b = A.new 现在,a和b都是A类的实例,并且可以访问此类中定义的所有实例方法.现在让我们说,我们想要添加一个额外的方法,只能通过a访问,而不能通过b访问(这在某些情况下可能很有用,但如果可能的话,请避免使用它).所有方法都在类中定义,因此我们似乎需要将它添加到类A中,但这样它也可以被b访问.在这种情况下,我们需要为对象创建一个实例类.为此,我们使用class<< <对象>句法: class << a def foo end end a.foo #=> nil b.foo #=> undefined method 简而言之,等级<< <对象>打开给定对象的实例类,允许为给定实例定义其他实例方法,这些方法在任何其他对象上都不可用. 现在,有了这样说:在Ruby中,类是类Class的最佳实例.这个: class A end 几乎相当于(差异在这里不重要) A = Class.new 因此,如果类是对象,则可以创建其实例类. class << A def foo end end A.foo #=> nil Class.new.foo #=> undefined method 它通常用于向给定的类添加所谓的类方法,但关键是实际上是在类的实例类上创建实例方法. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |