Ruby-数组、边界和引发异常

Ruby-数组、边界和引发异常,ruby,arrays,exception-handling,indexoutofboundsexception,Ruby,Arrays,Exception Handling,Indexoutofboundsexception,下面是我的脚本代码 如您所见,我有一个数组和一个索引。我将其传递给名为“raise\u clean\u exception”的块。它的整数部分实际上会引发一个非常好的标准错误异常。当我使用一个超出界限的索引时,我遇到了一个问题。因此,如果我的数组只有4个元素(0-3),并且我使用了9的索引,它不会引发异常,而是打印出一个空行,因为没有任何内容。为什么会这样 #!/usr/bin/ruby puts "I will create a list for you. Enter q to stop c

下面是我的脚本代码

如您所见,我有一个数组和一个索引。我将其传递给名为“raise\u clean\u exception”的块。它的整数部分实际上会引发一个非常好的标准错误异常。当我使用一个超出界限的索引时,我遇到了一个问题。因此,如果我的数组只有4个元素(0-3),并且我使用了9的索引,它不会引发异常,而是打印出一个空行,因为没有任何内容。为什么会这样

#!/usr/bin/ruby
puts "I will create a list for you.  Enter q to stop creating the list."
array = Array.new
i = 0
input = ''
print "Input a value: "  #get the value from the user
input = STDIN.gets.chomp
while input != 'q' do #keep going until user inputs 'q'
  array[i] = input  #store the value in an array of strings
  i += 1   #increment out index where the inputs are stored
  print "Input a value: "  #get the value from the user
  input = STDIN.gets.chomp
end  #'q' has been entered, exit the loop or go back through if not == 'q'

def raise_clean_exception(arr, index)
  begin
    Integer(index)
    puts "#{arr[index.to_i]}"
    # raise "That is an invalid index!"
  rescue StandardError  => e  # to know why I used this you can google Daniel Fone's article "Why you should never rescue exception in Ruby"
    puts "That is an invalid index!"
  end
  # puts "This is after the rescue block"
end

# now we need to access the array and print out results / error messages based upon the array index value given by the user
# index value of -1 is to quit, so we use this in our while loop
index = 0
arrBound = array.length.to_i - 1
while index != '-1' do
  print "Enter an index number between 0 and #{arrBound} or -1 to quit: "
  index = STDIN.gets.chomp
  if index == '-1'
    exit "Have a nice day!"
  end
  raise_clean_exception(array, index)
end

访问超出现有元素范围的数组元素将返回nil。这就是Ruby的工作方式

您可以在“puts”之前添加以下行以捕获该条件

raise StandardError if index.to_i >= arr.size

考虑使用StandardError的子类,
IndexError
,该子类特定于您遇到的问题。此外,如果索引超出范围,则使用
else
可防止打印空白,并且在方法中引发异常时,将暗示
begin…end

def raise_clean_exception(arr, index)
  Integer(index)
  raise IndexError if index.to_i >= arr.length
  rescue StandardError
    puts "That is an invalid index!"
  else
    puts "#{arr[index.to_i]}"
end

谢谢,这就是我想知道的。我没有意识到元素返回零,您回答了我的下一个问题,如何调整它。非常感谢!