Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "self" being returned in Ruby

Tags:

ruby

I'm following this Ruby tutorial here, and it's talking about Stacks and Queues http://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/33-advanced-arrays/lessons/86-stacks-and-queues#solution4117

It gives the following code for a stack

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

My question is: Why is it necessary to return "self" in the "push" method, but we do not have to return self in say the pop method? What is the distinction here?

Thanks!

like image 417
Ricky Avatar asked Jun 12 '26 01:06

Ricky


2 Answers

Array#push and Array#pop return different things. The first returns the modified array, while the second returns the popped element.

The reason you might not want to return the modified array is that it breaks encapsulation and exposes the internal state of your object. Still, we would like to chain our push calls (i.e. Stack.new.push(2).push(5)), so we return self (of type Stack) instead of nil or something else.

like image 168
Julien Langlois Avatar answered Jun 16 '26 06:06

Julien Langlois


It is due to difference in use case.

  • When you use push, you use it with the argument element, and you further know that the operation succeeds. Getting back the value of element from the method is not useful. Having a return value of self makes it more convenient such as allowing chaining of the methods.
  • When you use pop, in useful cases, you are not sure whether the array has an element in it (otherwise it falis), and what element you get by popping. And getting back the popped value is the purpose of using the method.

In other words, push is a "setter/modifyer" method whereas pop is a (destructive) "getter" method.

like image 41
sawa Avatar answered Jun 16 '26 06:06

sawa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!