我有一个可能为零的对象。在下一行中,我将根据某种条件动态获取对象的任何一个参数。我正在将object.try()与if else块一起使用。现在,我想使用send()以便实现一些有效的代码。
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
现在,我想避免使用if else梯子并使用send。
if mes_record.present?
mes_record.send("#{form}")
else
mes_record = 'not available'
end
我正在寻找类似try的东西。
mes_record.try("dynamically substitute the attribute name here.") || 'not available'
有帮助吗?!
尝试一个小时后,我想出了解决方案。
停止使用Rails try方法。
mes_record.try(:send,“#{form}”)|| '不可用'
更简洁的方法是:
mes_record.try(form.to_sym) || 'not available'