o9s
is a microblog
home archives search feed blogroll


The Many Ways To Declare Private Methods In Ruby

In the following examples, the method time? is public and the methods tick and move_hand are private.

The most common way is to declare all your public methods, add the keyword private and then all the following methods are declared as private. It’s similar to how it’s done in C++.

class GrandfatherClock

  def time?
  end

private

  def tick
  end

  def move_hand
  end

end

It’s also possible to declare all your methods without thinking about their scopes and at the bottom of the class, tell the compiler what’s private.

class GrandfatherClock

  def time?
  end

  def tick
  end

  def move_hand
  end

  private :tick, :move_hand

end

Since Ruby 2.1 (the current stable version is 2.5.0) it’s possible to prepend private to the method signature. It’s my personal favorite. It makes it very obvious what is private and what is not. It’s very similar to how it’s done in Java.

class GrandfatherClock

  def time?
  end

  private def tick
  end

  private def move_hand
  end

end
Posted on 2018-02-03   #ruby  






← Next post    ·    Previous post →