vowels_arr = ["a","e","i","o","u"]
p vowels_arr[vowels_arr.length] #=> nil
(0..(vowels_arr.length)).all? {|i| vowels_arr[i] <= vowels_arr[i + 1]}
#=> `<=': comparison of String with nil failed (ArgumentError)
当您将vowels_arr[vowels_arr.length]
元素传递给块时,即nil
. 在Ruby
数组中是0(zero)
基于的。因此vowels_arr.length
给出5
意味着元素在 的范围内(0..4)
。见下文:
vowels_arr = ["a","e","i","o","u"]
p vowels_arr[0] #=> "a"
p vowels_arr[1] #=> "e"
p vowels_arr[2] #=> "i"
p vowels_arr[3] #=> "o"
p vowels_arr[4] #=> "u"
p vowels_arr[5] #=> nil
p vowels_arr[6] #=> nil
(0..(vowels_arr.length))
意味着您正在传递到块0,1,2,3,4,5
,并且尝试访问5
给出nil
,就像在您的数组中的5th
索引是nil
. (0...(vowels_arr.length)).all? {|i| vowels_arr[i] <= vowels_arr[i + 1]}
通过以下调试查看代码失败的原因,each
以查看已传递给块的内容:
vowels_arr = ["a","e","i","o","u"]
(0...(vowels_arr.length)).each {|i| p vowels_arr[i],"--",vowels_arr[i+1]}
p (1...3).to_a
输出:
"a"
"--"
"e"
"e"
"--"
"i"
"i"
"--"
"o"
"o"
"--"
"u"
"u"
"--"
nil