HoboSupport is a mixed bag of core ruby extensions that have been extracted from the Hobo project


Object extensions


Like is_a? but multiple types to be checked in one go

>> "foo".is_one_of?(String, Symbol)
=> true
>> :foo.is_one_of?(String, Symbol)
=> true
>> 1.is_one_of?(String, Symbol)
=> false

Method call extensions

We have the “.” operator to call methods on objects. These extensions introduce two “special dots”.


._?.” only calls the method if the receiver is not nil. Otherwise it returns nil. So x._?.method(*args) is equivalent to (nil == x ? nil : x.method(*args)).

>> "foo"._?.length
=> 3
>> nil._?.length
=> nil

When the receiver is nil, any method with any arguments will return nil. You can use Ruby’s || idiom to provide a different value when nil.

>> expires = nil
>> expires._?.to_s( :default ) || "never"
=> "never"

Note that _? should always be followed by a method call. It is not intended to store the intermediate result. Don’t do this!

>> intermediate = nil._?


.try” only calls the method if the receiver responds to that method. Otherwise it returns nil. So x.try.method(*args) is equivalent to (x.respond_to?(:method) ? x.method(*args) : nil).

>> "foo".try.reverse
=> "oof"
>> :foo.try.reverse
=> nil

What’s the difference?

Use _? when you want to call a method but you know the receiver may be nil. Use try when you want to call a method but you know the receiver may not respond to it. For instance, you may use try to call a Rails 2.3 function that doesn’t exist on Rails 2.2. Note that nil responds to some functions that may surprise you.

>> nil.try.to_i
=> 0
>> nil._?.to_i
=> nil

ActiveSupport’s try

try and _? were added to HoboSupport before try was added to ActiveSupport. Unfortunately, the try in ActiveSupport is different. It behaves in a fashion similar to HoboSupport’s _?, but has a different signature:

>> nil.try(:foo)
=> nil
>> nil.try {|p| "(not available)"}
>> "(not available)"
>> "foo".try(:reverse)
>> "oof"

Edit this page