Seybo Glaux Seybo Glaux - 5 months ago 24x
Ruby Question

Why do we need question mark in this rails try block?

I'm reading

Rails Devise gem
documentation and it says:

If the page could potentially not have a current_user set then:

if current_user.try(:admin?) # do something end

I have tried it without question mark


and it works the same way returning

Do I miss something? Is there any difference and how can I see it?

max max

Ruby is somewhat unusual in that it lets you include a wide range of characters in the names of methods including ? and !.

They have no special significance to the interpreter but the language convention is that:

  • methods ending with ? are interrogative - they should ALWAYS return true or false.
  • methods ending with ! either mutate the object the are called on or may raise a exception.

So why does it matter at all? In this particular case it does not matter since your user class has an accessor for the admin instance variable created by ActiveRecord - just like any other column.

If it did not however current_user.try(:admin) would always return nil. Remember that instance variables are always private in Ruby until you provide an accessor*.

class User
  def initialize
    @admin = true

  def admin?
end # is always nil...

This is because User does not respond to :admin and .try prevents a NoMethodError and just returns nil instead.