2012-09-02 38 views
0
stanza_class.new(node.attributes if node.attributes) 

我传递一个变量,可能是一个方法中的零。 有没有一种在ruby中做这件事的美丽方式?Ruby通过属性,可能是零

+2

'node.attributes如果node.attributes'是没有意义的。 'node'可能是零吗?然后'node.attributes if node' – tokland

回答

0

如果您在使用Ruby on Rails,你可以使用try方法:

EG。

node.try(:attributes) 

这意味着,如果nodenil,它返回的nil而不是在NilClass缺少方法。

参考:http://api.rubyonrails.org/classes/Object.html#method-i-try

如果你不使用的轨道,就可以猴子自己修补Object类。并(在参考URL),选择猴子修补Rails的源代码是:

class Object 
    def try(*a, &b) 
    if a.empty? && block_given? 
     yield self 
    else 
     __send__(*a, &b) 
    end 
    end 
end 

如果你的意思是节点从来都不是零,但node.attributes可能是零,那么你可以这样做:

stanza_class.new(node.attributes) 

这是因为

stanza_class.new(nil) 

相当于

stanza_class.new() 

也就是说,未通过的参数默认设置为零。

0

我假设它是node其中可能是nil。这是非常地道:

stanza_class.new(node.attributes if node) 

虽然程序员用来Ick的可能会写:

stanza_class.new(node.maybe.attributes) 
0
stanza_class.new(*node.attributes)