0
我想写一些代码,将采取数字的数组并打印数字的范围的字符串表示形式。为什么我得到一个IndexError
def rng (arr)
str = arr[0].to_s
idx = 1
arr.each do |i|
next if arr.index(i) == 0
if arr[arr.index(i)-1] == i - 1
unless str[idx - 1] == "-"
str[idx] = "-"
#else next
end
#puts "if statement str: #{str}, idx: #{idx}"
else
str[idx] = arr[arr.index(i)-1].to_s
idx += 1
str[idx] = ","+ i.to_s
end
idx += 1
end
puts "str = #{str} and idx = #{idx}"
end
rng [0, 1, 2, 3, 8] #"0-3, 8"
我得到这个错误:
arrayRange_0.rb:9:in `[]=': index 3 out of string (IndexError)
任何人都可以解释,为什么?当我取消注释else next
它的作品。不知道为什么。