Topic: Question about ? (.nil?, .blank?, .include?)

What's the best way to explain what the "?" question mark does in ruby?

Take for instance this snippet of a view

<%= unless %>

To me that says "print the name of the user instance variable unless the name of the user instance variable is nil (or is it?)"

The ? seems to complicate things since it seems to me that you could just use

  <%= unless %>

"Do something unless do is nil."

Does the ? return true or false? Is the first example really saying "print the name of the user instance variable unless I(ruby) evaluate the name to be nil in which case return false"

I looked through "Why's" guide since he does a good job of explaining this kinda stuff but only found a brief little bit about it.

Re: Question about ? (.nil?, .blank?, .include?)

Since ruby allows the question mark to appear in the name of a method it's become convention to name all methods that return either a true or false value with that punctuation.

Rails has adopted this convention and that's why the following will return different values:
User.find(:first).email # returns ''
User.find(:first).email? # returns true

It's definitely weird to get used to - especially when doing this:

some_value.nil? ? 'something' : 'something else'

That always gets me.

Also, here's a breakdown on the three methods you mentioned.  I've rewritten each of the methods to show you generally how they work:

class Thing
  def nil?
     return (self  == nil) ? true : false
  def blank?
     return (self.nil? || self == 0 || self =='' || self == [] || self == {}) ? true : false
  def include?(obj)
    self.each |item_in_self|
      return true if obj == item_in_self 
    return false

Re: Question about ? (.nil?, .blank?, .include?)


Thanks danger, that really clears things up.  I almost asked about using ? with the ternary but it seems like using that is probably not such a great idea.

Re: Question about ? (.nil?, .blank?, .include?)

I think ruby's inclusion of punctuation in method names is great and I love the conventions that have sprung up from it.

? on the end of predicate methods and ! on the end of methods that alter in place is great. Really increases readability of code IMO. I especially like ! because I always give those methods a double take like "is that what I really want?"