又一个try方法的实现

有几篇讨论try的元编程参考
http://www.iteye.com/topic/169001
http://www.iteye.com/topic/351546

这里也提供一个gem,可以以比较简洁的方式实现,如try.a.b.c即可

gem install trydefault

测试例子如下(需要写在rb文件里测试,irb里面不行)

require ’try_default/default‘
def xxx
    "yes"
  end
p try.xxx == 'yes'
p (try.xxx.default "no") == 'yes'
p try.xxx.yyy.zzz.nil? == true
#不过暂时还实现不了try.xxx.yyy.zzz || "no"的效果,尽管支持nil?
#p (try.xxx.yyy.zzz || "no") == 'no' will fails, because try.xxx.yyy.zzz is a proxy object
p (try.xxx.yyy.zzz.default "no") == 'no'

#try后面不是方法而是是变量则要改成
#for variable
@xxx = "yes"
p try(@xxx) == 'yes'
p (try(@xxx).default "no") == 'yes'
p try(@xxx).yyy.zzz.nil? == true
p (try(@xxx).yyy.zzz.default "no") == 'no'
p @xxx.try.yyy.zzz.nil? == true
p "#{try.xxx}" == 'yes'
p "#{try.xxx.yyy.zzz}" == ''

#对于有些场合需要确保xxx.yyy有值的,还可以这样
#That will throw undefined method error for makr sure yyy not nil
#p xxx.yyy.try.zzz

你可能感兴趣的:(C++,c,C#,Ruby,Rails)