ruby - Why am I getting an IndexError -


i'm trying write code take array of numbers , print string representation of range of numbers.

def rng (arr)   str = arr[0].to_s    idx = 1   arr.each |i|      next if arr.index(i) == 0     if arr[arr.index(i)-1] == - 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} , idx = #{idx}" end  rng [0, 1, 2, 3, 8] #"0-3, 8" 

i error:

arrayrange_0.rb:9:in `[]=': index 3 out of string (indexerror) 

can explain why? when uncomment else next works. not sure why.

when error, str contains value 0- 2 characters long - therefore can't indexed position of 3.

add line before line 9, causing error:

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

it output:

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

Comments