2015-01-09 46 views
0

试图在方法传递一个块:传递字符串和块红宝石方法做

self.handler_method("pinterest", do |pinterest| 
    handle_facebook(pinterest.get_facebook[:username]) if pinterest.facebook_found? 
    handle_twitter(pinterest.get_twitter[:username]) if pinterest.twitter_found? 
end).call(username) 

这使返回错误:

syntax error, unexpected keyword_do_block (SyntaxError) 
       self.handler_method "pinterest", do |pinterest| 
               ^

我怎样才能修复它,使得它接受两个参数。我可以做内联块方式{}但宁愿用do, end

感谢

回答

3

扩大它应该是:

self.handler_method("pinterest") do |pinterest| 
    handle_facebook(pinterest.get_facebook[:username]) if pinterest.facebook_found? 
    handle_twitter(pinterest.get_twitter[:username]) if pinterest.twitter_found? 
end.call(username) 
+0

这是正确的!等待12分钟。但是为什么这会起作用,而不是在方法括号内 –

+0

因为块到方法应该在它们之外传递。 –

+0

从调用者的角度来看,该块不是方法参数。你只能将方法参数放在括号中(如果在Ruby中)。 'do ... end'然后总是遵循没有他们的论点。我在说“从调用者的角度来看”,因为在实现一个带有块的方法时,可以在方法签名中指定块作为参数。这是Ruby的不一致之处...... – awendt