ruby 切片不为零

标签 ruby

<分区>

对于四元素数组,[4] 返回nil,但[4, 0] 返回一个空数组。

array = [:peanut, :butter, :and, :jelly]
array[4] # => nil 
array[4, 0] # => [] 
array[5] # => nil 
array[5, 0] # => nil 

为什么 [4, 0] 不像 [5, 0] 那样返回 nil

Ruby 中数组切片的答案:寻找不合逻辑行为的解释(来自 Rubykoans.com)=> Graphical Explination of WHats Happening

最佳答案

这是一个特例。来自official docs (斜体是我的):

For start and range cases the starting index is just before an element. Additionally, an empty array is returned when the starting index for an element range is at the end of the array.

a = [ "a", "b", "c", "d", "e" ]
# ...
# special cases
a[5]                   #=> nil
a[6, 1]                #=> nil
a[5, 1]                #=> []

关于 ruby 切片不为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34979538/

相关文章:

javascript - 在 Ruby 注入(inject)的 JavaScript 中转义撇号?

ruby 哈希 : can't convert String into Integer TypeError

ruby - EM :Connection (em-synchrony) 内的光纤

c++ - 使用 Ruby on Rails 进行复杂算法

ruby - 无法将 jruby 版本从 1.5.6 更新到 1.7.2

ruby - 如何在 Ruby 中解析 A​​MF 数据?

ruby:数组中所有元素的索引小于给定值

mysql - 监控服务器上的应用程序

ruby - 只允许破折号和数字的正则表达式?

ruby - 检查散列是否有一个包含一些文本的键