def p.method_missing*_;p;end再来一个完整的代码实例:
第一次看,还是没有看的全明白。然后咱们来个格式化后的版本:
class NilClass
def method_missing *_
nil
end
end
别钻牛脚尖,非要一个字符字符对,看中间精华部分。此代码的作用是针对实例对象类如@some_hash,是个hash,
你想得到key=>value值时,出现nil时,提供的解决办法。
你可能希望这样的代码:if @some_hash[:some_key] # good looking version
# do something with @some_hash[:some_key]
end
但如果@some_hash是nil,上面的代码就会出exception了。
你不得不这么写:if @some_hash && @some_hash[:some_key] # correct version
# do something with @some_hash[:some_key]
end
# Egocentric nil不管怎么说,真的很优雅。ruby is awesome!
# code by Yohan, slightly edited and comments by me
# start ego mode block, usage:
# catch_nil do
# if @some_hash[:some_key].to_formatted_array[3]
# # do something
# end
# end
def catch_nil(&block)
# grip methods
ori_method_missing = NilClass.instance_method(:method_missing)
catch_method_missing = NilClass.instance_method(:catch_method_missing)
# activate ego mode
NilClass.send :define_method, :method_missing, catch_method_missing
# run code
yield
ensure
# no matter what happens: restore default nil behaviour
NilClass.send :define_method, :method_missing, ori_method_missing
end
#alias :egonil :catch_nil # ;)
# this is the ego nil
class NilClass
def catch_method_missing(m, *args, &block)
nil
end
end
详细看这里:
The 28 Bytes of Ruby Joy!
--tommy xiao
E-mail: xiaods(AT)gmail.com
没有评论:
发表评论