【发布时间】:2021-11-19 03:15:06
【问题描述】:
我会缩短这段代码。
def foo type, user
if type == "foo"
user.foo
elsif type == "bar"
user.bar
end
end
user 是 ActiveRecord 对象
type 是字符串“foo”或“bar”
如果我有更多types,那么我需要制作更多elsif。使用type 变量作为列名可以使其更短(不使用模型方法或任何其他附加代码)?比如:
user.{type} # ???
【问题讨论】:
-
类型总是等于方法名?如果是这样,您可以使用
user.public_send(type) -
是的,这正是我的意思!谢谢
标签: ruby-on-rails ruby activerecord