gpt4 book ai didi

ruby - 分配分支条件太高

转载 作者:数据小太阳 更新时间:2023-10-29 07:06:02 26 4
gpt4 key购买 nike

我有一个简单的类,它在初始化时接受一到八个参数。它将访问器设置为这些访问器以供以后使用。 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

但这似乎有点弱。

最佳答案

这是实现您想要做的事情的方法之一:

class Foo
attr_accessor(*%i[one two three four five six seven eight])

def initialize(p = {})
p.keys.each { |k| instance_variable_set("@#{k}", p.fetch(k, nil)) }
end
end

查看 Hash#fetch方法。

您也可以使用它来访问 p 变量的键值对,如果您决定使用一个而不是 8 个变量 (@p)


编辑

只是出于好奇写了这个版本(使用了一些元编程)——它会为添加的实例变量动态添加 attr_accessor:

class Foo
def initialize(p = {})
p.keys.each do |k|
instance_variable_set("@#{k}", p.fetch(k, nil))
self.class.__send__(:attr_accessor, k)
end
end
end

发生了什么,我们获取提供给 initialize 方法的参数(散列 p),获取它的键并从中创建实例变量,为每个变量分配相应的值到关键。然后我们为每个键定义 attr_accessor

a = Foo.new(a: 2, b: 3)
#=> #<Foo:0x00000002d63ad8 @a=2, @b=3>

关于ruby - 分配分支条件太高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34791575/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com