Ruby语法疑问:x[0...i]的作用及collect行代码逻辑解析
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 indexi. - 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:
- The range
(1..fruits.size)gives us the numbers 1, 2, 3, 4 (sincefruits.sizeis 4). collectiterates over each number in that range, passing it to the block asi:- 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"]
- When
collectgathers all these sliced sub-arrays into a new array, soprefixesends 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

