I'm trying to find a shorthand method for doing the following:

if row.respond_to?(:to_varbind_list)
  result << row.to_varbind_list.to_hash
else
  result << row.to_hash
end

And achieve it with something like this

row.try_if_respond_to(:to_varbind_list).to_hash

Basically row tries to call a method on itself, if that method doesn't exist then just return itself.

Maybe by overriding the Object class or something similar. I'm assuming it's pretty simple how to create my own.

Does Ruby already provide something that does this?

有帮助吗?

解决方案

No, ruby does not provide something like this. Also, the Rails try method does not do what you want, since it returns either nil or the method result, but never the original object.

I would say such a method would lead to ambivalent and rather unreadable code since the object that gets the message would be ambivalent. You can surely roll your own, but I find your original code is to the point. If you want to make it shorter in terms of code lines, use ternary operators:

result << (row.respond_to?(:to_varbind_list) ? row.to_varbind_list : row).to_hash
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top