You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby语法疑问:x[0...i]的作用及collect行代码逻辑解析

Understanding x[0...i] in Ruby's collect

Hey there! Let's unpack this Ruby syntax and how it works in the context of collect (which is just an alias for map, by the way—they do the exact same thing).

First, let's break down x[0...i] itself:

  • This is Ruby's array slicing syntax. The ... creates a left-closed, right-open range. That means it includes elements starting at index 0, and stops right before index i.
  • To contrast: If you used x[0..i] (with two dots), that would be a closed range—it includes both the start and end indices.

Now, let's tie this to collect with a concrete example. Suppose you have code like this:

fruits = ["apple", "banana", "cherry", "date"]
prefixes = (1..fruits.size).collect { |i| fruits[0...i] }

Here's exactly what happens step by step:

  1. The range (1..fruits.size) gives us the numbers 1, 2, 3, 4 (since fruits.size is 4).
  2. collect iterates over each number in that range, passing it to the block as i:
    • When i = 1: fruits[0...1] grabs elements from index 0 up to (but not including) 1 → ["apple"]
    • When i = 2: fruits[0...2] grabs elements 0 and 1 → ["apple", "banana"]
    • When i = 3: fruits[0...3] grabs elements 0, 1, 2 → ["apple", "banana", "cherry"]
    • When i = 4: fruits[0...4] grabs all elements (since index 4 is beyond the last element of the array) → ["apple", "banana", "cherry", "date"]
  3. collect gathers all these sliced sub-arrays into a new array, so prefixes ends up being:
    [["apple"], ["apple", "banana"], ["apple", "banana", "cherry"], ["apple", "banana", "cherry", "date"]]
    

The core purpose of x[0...i] in this collect context is to generate a prefix sub-array of the original array x, containing its first i elements. Pairing this with collect and a range of i values lets you generate all possible prefixes of the array in one go—this is super useful for tasks like building sequences, testing partial data sets, or generating combinations.

内容的提问来源于stack exchange,提问作者John Cowan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:58:18