我有一个可能为零的对象。在下一行中,我根据某些条件动态获取对象的任何一个参数。我在 if else 块中使用 object.try()。现在我想使用 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 阶梯并使用发送。
if mes_record.present?
mes_record.send("#{form}")
else
mes_record = 'not available'
end
我正在寻找类似尝试的东西。
mes_record.try("dynamically substitute the attribute name here.") || 'not available'
有什么帮助吗?!
最佳答案
尝试了一个小时后,我找到了解决方案。
向 Rails 尝试方法致敬。
mes_record.try(:send, "#{form}") || '无法使用'
关于ruby-on-rails - Rails - 'send' 和 'try' 的混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29194619/