respond to - Ruby (try_if)_respond_to. Does it exist? -


i'm trying find shorthand method doing following:

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

and achieve this

row.try_if_respond_to(:to_varbind_list).to_hash 

basically row tries call method on itself, if method doesn't exist return itself.

maybe overriding object class or similar. i'm assuming it's pretty simple how create own.

does ruby provide this?

no, ruby not provide this. also, rails try method not want, since returns either nil or method result, never original object.

i such method lead ambivalent , rather unreadable code since object gets message ambivalent. can surely roll own, find original code point. if want make shorter in terms of code lines, use ternary operators:

result << (row.respond_to?(:to_varbind_list) ? row.to_varbind_list : row).to_hash 

Comments