I have an object which could be nil. In the next line i am getting any one of the object's argument dynamically based on some condition. I was using object.try() with if else block. Now I want to use send() so that I can achieve some efficient code.
form_name = 'parent' ( received from argument )
mes_record = Mark.first ( this can be nil )
if x == condition_1
mes_record.parent
elsif x == condition_2
mes_record.brother
elsif x == condition_3
mes_record.sister
else
mes_record.father
end
Now I want to avoid the if else ladder and use send.
if mes_record.present?
mes_record.send("#{form}")
else
mes_record = 'not available'
end
I am searching for something like try.
mes_record.try("dynamically substitute the attribute name here.") || 'not available'
Any help?!
After trying for one hour i figured out the solution.
Hats off to Rails try method.
mes_record.try(:send, "#{form}") || 'not available'
A bit cleaner way is simply:
mes_record.try(form.to_sym) || 'not available'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With