开发者社区> 问答> 正文

Ruby中的数组切片:不合逻辑行为的解释(摘自Rubykoans.com)

我在进行Ruby Koans的练习时,被以下发现我无法解释的Ruby怪癖震惊:

array = [:peanut, :butter, :and, :jelly]

array[0] #=> :peanut #OK! array[0,1] #=> [:peanut] #OK! array[0,2] #=> [:peanut, :butter] #OK! array[0,0] #=> [] #OK! array[2] #=> :and #OK! array[2,2] #=> [:and, :jelly] #OK! array[2,20] #=> [:and, :jelly] #OK! array[4] #=> nil #OK! array[4,0] #=> [] #HUH?? Why's that? array[4,100] #=> [] #Still HUH, but consistent with previous one array[5] #=> nil #consistent with array[4] #=> nil
array[5,0] #=> nil #WOW. Now I don't understand anything anymore... 那么为什么array[5,0]不等于array[4,0]?从第(length + 1)个位置开始时,数组切片为何有这种奇怪的表现?

展开
收起
保持可爱mmm 2020-01-16 15:38:44 528 0
1 条回答
写回答
取消 提交回答
  • 我在进行Ruby Koans的练习时,被以下发现我无法解释的Ruby怪癖震惊:

    array = [:peanut, :butter, :and, :jelly]

    array[0] #=> :peanut #OK! array[0,1] #=> [:peanut] #OK! array[0,2] #=> [:peanut, :butter] #OK! array[0,0] #=> [] #OK! array[2] #=> :and #OK! array[2,2] #=> [:and, :jelly] #OK! array[2,20] #=> [:and, :jelly] #OK! array[4] #=> nil #OK! array[4,0] #=> [] #HUH?? Why's that? array[4,100] #=> [] #Still HUH, but consistent with previous one array[5] #=> nil #consistent with array[4] #=> nil
    array[5,0] #=> nil #WOW. Now I don't understand anything anymore... 那么为什么array[5,0]不等于array[4,0]?从第(length + 1)个位置开始时,数组切片为何有这种奇怪的表现? 问题来源于stack overflow

    2020-01-16 15:38:59
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Python系列直播第一讲——Python中的一切皆对象 立即下载
Python 脚本速查手册 立即下载
Python第五讲——关于爬虫如何做js逆向的思路 立即下载