Ruby中二维数组中的超出范围值

时间:2022-06-24 12:18:49

I was aware that out of range value for arrays in Ruby is nil; however I encountered an issue when I used two dimensional array. Here's a simple code to illustrate an issue I'm having.

我知道Ruby中数组的超出范围值是零;但是当我使用二维数组时遇到了一个问题。这是一个简单的代码来说明我遇到的问题。

a = [1]
b = [[ 1, 2 ], [ 3, 4]]
puts a[0]   #outputs 1
puts b[0][0] #outputs 1
puts a[100] == nil #outputs true
puts b[100][100] == nil #undefined method `[]' for nil:NilClass (NoMethodError)

Is there a special syntax that is required or am I missing something here?

是否需要特殊的语法,或者我在这里遗漏了什么?

1 个解决方案

#1


3  

b[100] is out of range so the result is nil.
You are then calling nil[100] which raises an error since nil does not have any [] method.

b [100]超出范围,结果为零。然后你调用nil [100]引发错误,因为nil没有任何[]方法。

#1


3  

b[100] is out of range so the result is nil.
You are then calling nil[100] which raises an error since nil does not have any [] method.

b [100]超出范围,结果为零。然后你调用nil [100]引发错误,因为nil没有任何[]方法。