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

Popular posts from this blog

php - cannot display multiple markers in google maps v3 from traceroute result -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -