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 isself
even though it's not "mentioned"
- Explicit:
- Private methods, the receiver is always
self
. It is not possible to callvar_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 methodfoo
as protected, andbar(var)
as public. - If
var
is of typeMyClass
then explicit invocation is possible:var.foo
from withinbar(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.
- Class
- Using
send(:method_name)
allows invocation of any private or protected method, because inside of that class invocation ofmethod_name
will always satisfy the implicit invocation requirement of private and protected.
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.