That’s pretty cool, but I’d prefer it return a proxy object for all non-nil
objects that just relays the method call, and for nil a proxy that always
returns nil, ala:
hash[key].try.downcase
Like this?
require ‘singleton’
class NilProxy
include Singleton
def method_missing(*a,&b) end
end
class Object
def try
self
end
end
class NilClass
def try
NilProxy.instance
end
end
[“Foo”, nil, “Bar”].each do |x|
p x.try.downcase
end
It works because (… if …) returns nil if the condition is false.
While that would clearly work, it makes me a little nervous as it
isn’t immediately obvious, to me at least. Most likely I just haven’t
spent enough time with Ruby.
On Mon, 11 Oct 2010 23:04:59 -0500, Joel VanderWerf
var = (hash[key].downcase if hash[key])
It works because (… if …) returns nil if the condition is false.
While that would clearly work, it makes me a little nervous as it
isn’t immediately obvious, to me at least. Most likely I just haven’t
spent enough time with Ruby.
I agree. It reduces readability, and it’s easy to forget the parens.
Obviously I could do this, but I’m trying to keep it on one line:
var = hash[key]
var = var.downcase unless var.nil?
I’m not sure if this is the most common idiom, but you can write a
helper method like “try” that chains method calls but aborts nicely to
nil as soon as an object dereference (or the primary object itself)
evaluates to nil.
The example below is slightly fancier than you might need, as it
supports multiple dereferences. Scroll down to the bottom to see its
usage.
$ cat foo.rb
def try(obj, *args)
for arg in args
return nil if obj.nil?
obj = obj.send(arg)
end
return obj
end
class Mission
end
class Department
def name
‘HR’
end
def mission
return nil
end
end
class Employee
def department
return Department.new()
end
is World Sight Day, 14th October 2010 get your eyes tested by your
nearest optician and get the best possible discount. For more details
check Redirecting...