Tag: getter setter

Ruby / Rails:了解ruby getter-setter方法和实例

我是ruby和编程的新手,我正在努力掌握一些关键概念。 鉴于我有一个类狗,具有以下特点。 class Dog attr_accessor :type, :popularity, :total def initialize(type = nil) @type = type end def total_dogs Dog.count end def total Dog.where(:type => self.type).size end def popularity total.to_f/total_dogs end end 我想要了解的是,ruby如何通过getter / setter方法将属性持久化到实例。 我清楚地知道,如果我实例化一个新实例然后将属性保存到该实例,那么这些属性就与该实例相关联,因为如果我查看该对象,则属性如下所示: @dog = Dog.new @dog => # 我很容易理解,当我传递@dog对象时,总是将@type属性作为nil。 但是,我无法理解的情况是我将这个@dog对象传递给另一个类。 就像我做的那样: Owner.new(@dog) 当我在所有者类中并且我打电话给@ dog.popularity时,它如何知道该实例的受欢迎程度值? 在运行时是否处理了所有方法,然后该实例总是与当时的值绑定? 抱歉,如果这没有意义,或者我离开了。

Ruby attr_accessor与getter / setter基准:为什么访问器更快?

我刚刚对等效的getter / setter-methods测试了attr_accessor: class A # we define two R/W attributes with accessors attr_accessor :acc, :bcc # we define two attributes with getter/setter-functions def dirA=(d); @dirA=d; end def dirA; @dirA; end def dirB=(d); @dirB=d; end def dirB; @dirB; end end varA = A.new startT = 0 dirT = 0 accT = 0 # now we […]