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
它的作品。不知道爲什麼。