0

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?

Oktav
  • 2,143
  • 2
  • 20
  • 33
  • Something that would help when deciding how to handle this - in what situations that happen in your code, will `row` *not* respond to `to_varbind_list`? Knowing the answer to that may point you an entirely different solution than this defensive code – Neil Slater May 14 '13 at 10:06
  • @NeilSlater thanks. The `row` will not respond to `to_varbind_list` if it is already an instance of `VarBindList`. To make it clearer, `row` can be either a `Varbind` or a `VarBindList` – Oktav May 14 '13 at 10:09
  • IMO then your code in the question is accurate as-is. It supports two varieties of data object, and differentiates between them by duck typing. Beat Richartz's answer compresses it into one line, but you could also start `result = if . . .` or `result = case . . .` to make your own code slightly shorter, and still easiest to read. – Neil Slater May 14 '13 at 10:16
  • Yes, in fact I accepted his answer as it was what I asked for. I was looking for more Ruby-ish code :) but this will do. – Oktav May 14 '13 at 10:19

1 Answers1

2

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
Beat Richartz
  • 9,474
  • 1
  • 33
  • 50