Skip to content

Instantly share code, notes, and snippets.

@pdmholden
Last active April 8, 2017 19:35
Show Gist options
  • Save pdmholden/74b48424ee137a0decd3b06ea044bf5a to your computer and use it in GitHub Desktop.
Save pdmholden/74b48424ee137a0decd3b06ea044bf5a to your computer and use it in GitHub Desktop.
Things I keep forgetting

Public/Private/Protected

This is all about the receiver.

  • Public is the simple case, these messages can be sent to any receiver, explicit or implicit.
    • Explicit: var_name.method_name; self.method_name.
    • Implicit: (inside a class, just calling method_name) because the receiver is self even though it's not "mentioned"
  • Private methods, the receiver is always self. It is not possible to call var_name.method_name, ie, only implicit invocation is possible.
    • The result is that these methods can only be called (with implicit receiver) from within the class in which they are defined. But this is not about information hiding, it is about the receiver of the message.
  • Protected methods are like private except that explicit receivers are allowed when the message is sent from a class of the same type.
    • Class MyClass defines method foo as protected, and bar(var) as public.
    • If var is of type MyClass then explicit invocation is possible: var.foo from within bar(var).
    • The result is that for instances of the same class, they can access each other's protected methods as if they were public. Again, this is about the receiver of the message, not information hiding.
  • Using send(:method_name) allows invocation of any private or protected method, because inside of that class invocation of method_name will always satisfy the implicit invocation requirement of private and protected.

Existential Methods

Method Behaviour Source
nil? true for anything that is nil. 0 and false are not nil. Ruby
empty? true for anything that is empty. For example, arrays, hashes and strings. Throws NoMethodError on everything else (eg, try it on an integer). The boolean false is empty. Ruby
blank? Covers everything that either nil? or empty? cover. Rails
present? Negation of blank? Rails

Note the difference between calling these methods on an object_id from ActiveRecord, vs on the reference to the object itself. For example, given an id of 0, the results are not necessarily as expected. Also, be careful:

irb(main):050:0* false.blank?
=> true
irb(main):051:0> [].nil?
=> false
irb(main):052:0> [].blank?
=> true
irb(main):053:0> [].present?
=> false

See also, and of course the documentation for Ruby and Rails.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment