gpt4 book ai didi

Ruby String 变量为 .is_a 返回 true?(Array)

转载 作者:太空宇宙 更新时间:2023-11-03 18:20:52 26 4
gpt4 key购买 nike

我有一个方法可以获取数组或字符串

为了使该方法正常工作,我需要将该字符串转换为数组。因为它有时会得到字符串,所以我想让它检查变量是否是数组,如果不是,则将其转换为数组。所以我做了以下事情:

unless variablename.is_a?(Array)
variablename = variablename.lines.to_a
end

第二行失败,我收到一个 ruby​​ 错误,指出“lines”对数组对象不可用。

我也试过 .kind_of?结果相同

我得到了答案,但我还想弄清楚我到底在问什么。我正在测试 variablename 是否是一个数组。由于某种原因,当 variablename 是一个数组时,它仍然运行并且第二行失败并出现以下错误: #Array:0x000000021382b8 (NoMethodError) 的未定义方法“行”

最佳答案

def do_stuff(x)
x = x.lines.to_a if x.is_a? String
x
end

data = [
"hello\nworld",
[1, 2, 3]
]

data.each do |item|
p do_stuff item
end

现在,除非:

def do_stuff(x)
unless x.is_a?(Array)
x = x.lines.to_a
end
x
end

data = [
"hello\nworld",
[1, 2, 3],
['a', 'b']
]

data.each do |item|
p do_stuff item
end

--output:--
["hello\n", "world"]
[1, 2, 3]
["a", "b"]

但是,在对象上调用 String 方法之前检查 String 对象比检查不是 Array 更有意义。

关于Ruby String 变量为 .is_a 返回 true?(Array),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18662608/

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