【发布时间】:2016-01-14 14:05:10
【问题描述】:
我有一个简单的类,它在初始化时接受一到八个参数。它将访问器设置为这些以供以后使用。 Rubocop 正试图以 ABC 太高为由逮捕我,但我不确定我所做的是否真的有什么问题。这是我在初始化时禁用检查的情况吗?
class Foo
attr_accessor :one, :two, :three, :four
attr_accessor :five, :six, :seven, :eight
def initialize(p={})
@one = p[:one] if p[:one].present?
# ...
@eight = p[:eight] if p[:eight].present?
end
end
我对减小大小的唯一想法是在初始化时遍历我的所有 attr_accessors,查看在 has 中是否有相应的符号通过,如果有,则分配它。
class Foo
attr_accessor :one, :two, :three, :four
attr_accessor :five, :six, :seven, :eight
def initialize(p={})
instance_variables.each do |variable|
send("@#{variable}") = p["#{send(variable)}".to_sym] if p["#{send(variable)}".to_sym].present?
end
end
end
但这似乎有点弱。
【问题讨论】:
标签: ruby coding-style rubocop