为什么在Ruby中返回"self"

Ric*_*cky 2 ruby

我在这里关注这个Ruby教程,它正在谈论堆栈和队列 http://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/33-advanced-arrays/lessons/86-stacks-和队列#solution4117

它为堆栈提供以下代码

class Stack
  def initialize
    @store = Array.new
  end

  def pop
   @store.pop
  end

  def push(element)
    @store.push(element)
    self
  end

  def size
    @store.size
  end
end
Run Code Online (Sandbox Code Playgroud)

我的问题是:为什么有必要在"推"方法中返回"自我",但我们不必返回自我说pop方法?这有什么区别?

谢谢!

Jul*_*ois 7

Array#pushArray #pop返回不同的东西.第一个返回修改后的数组,第二个返回弹出的元素.

您可能不想返回修改后的数组的原因是它破坏了封装并暴露了对象的内部状态.不过,我们想连接我们的推送调用(即Stack.new.push(2).push(5)),所以我们返回self(类型Stack)而不是nil或其他东西.