gpt4 book ai didi

ruby - 在数组中的字符串上使用 .split

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

对于像 12,34,56;78,91;50,60; 这样的输入

我想用分号分隔字符串,然后用逗号分隔那些字符串

例如:

puts "Input: "
input = gets.chomp
s_array = input.split(";")
for i in 0..s_array.size
puts s_array[i].split(",")
end

它会用 puts 成功打印但是在我得到一个错误之后

undefined method 'split' for nil:NilClass <NoMethodError>

这个错误的原因是什么?

最佳答案

.. 更改为 ...

for i in 0...s_array.size

使用 .. 创建一个范围是包容性的,而 ... 不是,例如

1..5  # => 1,2,3,4,5
1...5 # => 1,2,3,4

因此变量 i 溢出数组,在您的情况下,如果数组大小为 5,则 array_s[5] 将为空。

关于ruby - 在数组中的字符串上使用 .split,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21843391/

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