Ruby 方法链接(初学者)
Ruby Method Chaining (beginner)
我写了下面的代码:
class Pet
attr_accessor :breed, :name, :weight
def initialize(breed, name, weight)
@breed = breed
@name = name
@weight = weight
end
def show_pet
p "Your pet is a #{@breed}, and their name is #{@name}. They weigh #{@weight} lbs."
end
def set_weight(weight)
@weight += weight
self
end
end
pet1 = Pet.new("Chihuahua", "Jill", 5)
pet1.set_weight(5).show_pet
但我不完全理解它是如何工作的,主要是 self
部分。我希望有人能指出我对方法链的一个很好的解释。
在您的示例中,@weight
是一个实例变量,set_weight 是一个实例方法,它向实例变量 @weight
.
添加权重
self
returns class 的实例更新了 @weight
。
然后 show_pet
方法调用返回的实例并打印其值。
show_pet
是 Pet
的实例方法(就像 set_weight
),因此它只能在 Pet
的实例上调用。当您想在 set_weight
之后调用此方法时,set_weight
需要 return 调用它的 Pet
的实例。
self
是您在 set_weight(weight)
中设置的 return 值,在实例方法中,这是对 Pet
实例的引用调用方法。因此,每当 Pet
的实例调用该方法时,它 return 就是实例本身。
为了更清楚地看到这一点,您可以通过以下方式进行一些实验:
class Pet
...
def return_instance
self
end
end
pet1 = Pet.new('Chihuaha', 'Jill', 5)
pet1 == pet1.return_instance # => true
如果您是初学者,有几件事需要考虑。
方法中的最后一个值调用是方法的 return 值。在你的例子中:
def set_weight(weight)
@weight += weight
self
end
等同于:
def set_weight(weight)
@weight += weight
return self # <- with return
end
然后,关于self,如果你习惯了其他语言,你可能看到关键字this,它是等价的。
它是您当前使用的 class 实例的引用。
当你在 returning self 时,你可以像这样链接调用:
rex_the_dog = Pet.new nil, 'rex', 20 #create rex_the_dog an instance of Pet
rex_the_dog.set_weight(3).set_weight(2) #As you return self, you can chain call like this
rex_the_dog.weight #return 25 (20 : set on init + 2 : first set_weight call + 3 : second set_weight call)
我写了下面的代码:
class Pet
attr_accessor :breed, :name, :weight
def initialize(breed, name, weight)
@breed = breed
@name = name
@weight = weight
end
def show_pet
p "Your pet is a #{@breed}, and their name is #{@name}. They weigh #{@weight} lbs."
end
def set_weight(weight)
@weight += weight
self
end
end
pet1 = Pet.new("Chihuahua", "Jill", 5)
pet1.set_weight(5).show_pet
但我不完全理解它是如何工作的,主要是 self
部分。我希望有人能指出我对方法链的一个很好的解释。
在您的示例中,@weight
是一个实例变量,set_weight 是一个实例方法,它向实例变量 @weight
.
添加权重
self
returns class 的实例更新了 @weight
。
然后 show_pet
方法调用返回的实例并打印其值。
show_pet
是 Pet
的实例方法(就像 set_weight
),因此它只能在 Pet
的实例上调用。当您想在 set_weight
之后调用此方法时,set_weight
需要 return 调用它的 Pet
的实例。
self
是您在 set_weight(weight)
中设置的 return 值,在实例方法中,这是对 Pet
实例的引用调用方法。因此,每当 Pet
的实例调用该方法时,它 return 就是实例本身。
为了更清楚地看到这一点,您可以通过以下方式进行一些实验:
class Pet
...
def return_instance
self
end
end
pet1 = Pet.new('Chihuaha', 'Jill', 5)
pet1 == pet1.return_instance # => true
如果您是初学者,有几件事需要考虑。
方法中的最后一个值调用是方法的 return 值。在你的例子中:
def set_weight(weight)
@weight += weight
self
end
等同于:
def set_weight(weight)
@weight += weight
return self # <- with return
end
然后,关于self,如果你习惯了其他语言,你可能看到关键字this,它是等价的。 它是您当前使用的 class 实例的引用。
当你在 returning self 时,你可以像这样链接调用:
rex_the_dog = Pet.new nil, 'rex', 20 #create rex_the_dog an instance of Pet
rex_the_dog.set_weight(3).set_weight(2) #As you return self, you can chain call like this
rex_the_dog.weight #return 25 (20 : set on init + 2 : first set_weight call + 3 : second set_weight call)