From: Robert Klemme Date: 2007-08-20T18:06:28+09:00 Subject: Re: Emulating a Groovy feature? 2007/8/18, John Wells : > Guys, > > There's something called Safe Navigation in Groovy (http://groovy.codehaus.org/Statements#Statements-Safenavigation) that I find very appealing. > > So, Groovy will allow you to safely walk an object graph, even if that graph has nulls in it (the walk will short circuit): > > def foo = null > def bar = foo?.something?.myMethod() > assert bar == null > > Is there an easy way to hack an equivalent out in Ruby? Try this in IRB class Object class Holder def __ref() @ref end def initialize(ref,&b) @ref = ref instance_eval(&b) end def method_missing(s,*a,&b) @ref = @ref.send(s,*a,&b) rescue nil self end end def safe(&b) Holder.new(self,&b).__ref end end F = Struct.new :name f=F.new "foo" f.safe { name.size > 10 } f.safe { name.xxx } Not too nice though... Kind regards robert