I have a method that will either get an array or a string
For the method to work correctly, I need to convert that string to an array. Since it will sometimes get string, I wanted to have it check if the variable is an array, and if not convert it to an array. So I did the following:
unless variablename.is_a?(Array)
variablename = variablename.lines.to_a
end
The second line of this fails and I get a ruby error that 'lines' is not available to an array object.
I also tried .kind_of? with same results
I got my answer but I also wanted to clear up what exactly I was asking. I am testing to see if variablename is an array. For some reason when variablename is an array, it still runs and than the second line fails with the following error: undefined method `lines' for #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
Now, with unless:
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"]
But it makes more sense to check for a String object before calling a String method on the object than checking for not an Array.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다