2016-01-24 64 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" 

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

相关问题