为什么我会得到一个IndexError

时间:2016-01-24 21:25:38

标签: ruby

我试图编写一些代码,这些代码将采用一组数字并打印数字范围的字符串表示。

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它的工作原理时。不知道为什么。

2 个答案:

答案 0 :(得分:1)

当您收到该错误时,str包含的值0-只有2个字符长 - 因此无法将其编入3的位置。

在第9行之前添加此行,这会导致您的错误:

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

将输出:

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

答案 1 :(得分: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"

与之前的答案相同,您的索引位于字符串

之外