Class: NilClass

Inherits:
Object show all
Defined in:
lib/ruby-try.rb

Instance Method Summary collapse

Instance Method Details

#try(*args) ⇒ Object

Calling try on nil returns nil It becomes specially helpful when navigating through associations that may return nil.

nil.try(:name) # => nil

Without try

@person && !@person.children.blank? && @person.children.first.name

With try

@person.try(:children).try(:first).try(:name)


46
47
48
# File 'lib/ruby-try.rb', line 46

def try(*args)
  nil
end

#try!(*args) ⇒ Object



61
62
63
# File 'lib/ruby-try.rb', line 61

def try!(*args)
  nil
end

#try?(*args) ⇒ Boolean

Calling try? on nil returns false With try?

@person.try(:children).try(:first).try?(:has_dark_hairs?)

Returns:

  • (Boolean)


53
54
55
56
57
58
59
# File 'lib/ruby-try.rb', line 53

def try?(*args)
  if args.first =~ /[?]$/
   false
  else
    raise ArgumentError, "For non-boolean methods use only try()"
  end
end