代码之家  ›  专栏  ›  技术社区  ›  Brian Ruff

Ruby方法链接(初学者)

  •  -1
  • Brian Ruff  · 技术社区  · 7 年前

    我写了下面的代码:

    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 部分我希望有人能给我一个很好的解释方法链接。

    3 回复  |  直到 7 年前
        1
  •  1
  •   GPif    7 年前

    如果你是初学者,有几件事需要考虑。

    方法中的最后一个值调用是方法的返回值。在您的示例中:

    def set_weight(weight)
        @weight += weight
        self
    end
    

    相当于:

    def set_weight(weight)
        @weight += weight
        return self # <- with return
    end
    

    然后,关于 自己 ,如果你习惯了其他语言,你可能已经看到了关键字 ,它是等效的。 它是您当前使用的类实例的引用。

    自己 你可以像这样连接通话:

    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)
    
        2
  •  1
  •   sawa    7 年前

    show_pet 是的实例方法 Pet set_weight ),因此只能在的实例上调用它 宠物 . 当您想在之后调用此方法时 设置重量 正如你所做的那样, 设置重量 需要返回的实例 宠物 它被调用了。

    self 是您在中设置的返回值 set_weight(weight) ,在实例方法中,这是对 宠物 实例调用方法。所以每当 调用该方法,它将返回实例本身。

    为了更清楚地看到这一点,您可以通过这样做进行一些实验:

    class Pet 
      ...
      def return_instance
        self
      end
    end
    
    pet1 = Pet.new('Chihuaha', 'Jill', 5)
    pet1 == pet1.return_instance # => true
    
        3
  •  0
  •   engineersmnky    7 年前

    在您的示例中 @weight 是一个实例变量,set_weight是一种向实例变量添加权重的实例方法 @重量 .
    self 返回具有更新的 @重量

    这个 show_pet 方法然后调用返回的实例并打印其值。