Ruby 习惯用法:方法调用或默认
在 Ruby 中执行此操作的正确方法是什么?
def callOrElse(obj, method, default)
if obj.respond_to?(method)
obj.__send__(method)
else
default
end
end
What's the proper way of doing this in Ruby?
def callOrElse(obj, method, default)
if obj.respond_to?(method)
obj.__send__(method)
else
default
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为它还没有作为答案提供:
与@slhck一样,当我知道 obj 有合理的机会不会响应方法时,我可能不会使用它,但它是一个选项。
Because it hasn't been offered as an answer:
As with @slhck, I probably wouldn't use this when I knew there was a reasonable chance that obj won't respond to method, but it is an option.
所以你想要类似于 x = obj.method || 的东西默认? Ruby 是构建您自己的自下而上结构的理想语言:
也许您不喜欢这种使用符号的间接调用?没问题,然后查看 Ick 的
maybe
样式并使用代理对象(你可以弄清楚实现):旁注:我不是OOP专家,但我的理解是你应该事先知道你正在调用的对象是否确实有这样的方法。或者
nil
是您想要控制不向其发送方法的对象吗?在这种情况下,Ick 已经是一个很好的解决方案:object_or_nil.maybe.method ||默认
So you want something similar to
x = obj.method || default
? Ruby is an ideal language to build your own bottom-up constructions:Maybe you don't like this indirect calling with symbols? no problem, then look at Ick's
maybe
style and use a proxy object (you can figure out the implementation):Side note: I am no OOP expert, but it's my understanding that you should know whether the object you are calling has indeed such method beforehand. Or is
nil
the object you want to control not to send methods to? Im this case Ick is already a nice solution:object_or_nil.maybe.method || default
我可能会去
I'd probably go for
你可以这样做:
“&”在这里充当“也许”。也许它有什么,也许没有。当然,如果没有,它只会返回 nil,并且不会运行其后面的方法。
You can do something like this:
the '&' acts as a Maybe here. Maybe it has something, maybe it doesn't. Of course, if it doesn't, it will just return nil and would not run the method that comes after it.