我有一个方法可以获得数组或字符串
要使方法正常工作,我需要将该字符串转换为数组。 由于它有时会得到字符串,我想让它检查变量是否是一个数组,如果没有将它转换为数组。所以我做了以下事情:
unless variablename.is_a?(Array)
variablename = variablename.lines.to_a
end
第二行失败了,我得到一个ruby错误,'lines'对数组对象不可用。
我也试过.kind_of?结果相同
我得到了答案,但我也想清楚我究竟在问什么。 我正在测试看看variablename是否是一个数组。由于某种原因,当variablename是一个数组时,它仍然运行,而第二行失败并出现以下错误: #Array的未定义方法`lines':0x000000021382b8(NoMethodError)
答案 0 :(得分:3)
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更有意义。
答案 1 :(得分:0)
to_a
之后您不需要lines
。它总是一个数组。你可以这样做:
case variablename
when Array then variablename
when String then variablename.lines
else p variablename.class # For debugging. This should not happen.
end
<小时/> 通过检查
#Array:0x000000021382b8
查看您的错误消息,variablename
可能不是Array
。
答案 2 :(得分:0)
我不会检查类型(is_a? String
),而是检查对象是否响应转换所需的方法。假设你想要迭代作为一个行数组或一个(多行)字符串提供的行,这样的东西就可以工作:
def do_stuff(lines)
lines = lines.each_line if lines.respond_to?(:each_line)
lines.each do |line|
# do stuff
end
end