gpt4 book ai didi

ruby - 使属性始终为数组的最佳方法?

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

我正在使用我的 MOO 项目自学测试驱动设计,它带我去了很多有趣的地方。例如,我写了一个测试,说特定对象的属性应该总是返回一个数组,所以 --

t = Thing.new("test")
p t.names #-> ["test"]

t.names = nil
p t.names #-> []

我的代码没问题,但对我来说似乎不是很 ruby :

class Thing

def initialize(names)
self.names = names
end

def names=(n)
n = [] if n.nil?
n = [n] unless n.instance_of?(Array)

@names = n
end

attr_reader :names
end

是否有更优雅、类似 Ruby 的方式来做到这一点?
(注意:如果有人想告诉我为什么这是一个愚蠢的测试,那也很有趣......)

最佳答案

我想指出的是,已经有一个内置方法可以做你想做的事!它叫做Array() .要问自己的问题是:可转换为数组的类(如 0..42)会怎样?

我觉得大多数 Rubyist 都期望他们会被转换。所以:

class Thing
attr_accessor :names

def initialize(names)
self.names = names
end

def names=(values)
@names = Array(values)
end
end

你会得到相同的结果,例如:

t = Thing.new("car")
t.names #-> ["car"]

t.names = nil
t.names #-> []

t.names = 42
t.names #-> [42]

t.names = [1, 2, 3]
t.names #-> [1, 2, 3]

t.names = 1..3
t.names #-> [1, 2, 3] # Is this what you want, or not?

关于ruby - 使属性始终为数组的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2431864/

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