2016-01-24 65 views
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它的作品。不知道爲什麼。

回答

1

當你得到這個錯誤,str包含值0-這是長僅2個字符 - 因此它不能被索引到的3

位置線9之前加入這一行,這是造成你的錯誤:

puts "str = #{str}, idx = #{idx}" 

這將輸出:

str = 0, idx = 1 
str = 0-, idx = 3 
0

這裏是你如何能做到這一點:

def rng(arr) 
    ranges = [] 
    arr.each do |v| 
    if ranges.last && ranges.last.include?(v-1) 
     # If this is the next consecutive number 
     # store it in the second element 
     ranges.last[1] = v 
    else 
     # Add a new array with current value as the first number 
     ranges << [v] 
    end 
    end 
    # Make a list of strings from the ranges 
    # [[0,3], [8]] becomes ["0-3", "8"] 
    range_strings = ranges.map{|range| range.join('-') } 
    range_strings.join(', ') 
end 


p rng [0, 1, 2, 3, 8] 
# results in "0-3, 8" 

像前面的回答說的那樣,你的索引超出了字符串

相關問題