题
通过列表在Python我可以使用以下代码返回它的一部分:
foo = [1,2,3,4,5,6]
bar = [10,20,30,40,50,60]
half = len(foo) / 2
foobar = foo[:half] + bar[half:]
由于红宝石做一切在阵列我不知道是否有类似的东西。
解决方案
是,Ruby有非常相似的阵列切片语法到Python。下面是数组索引方法的ri
文档:
--------------------------------------------------------------- Array#[]
array[index] -> obj or nil
array[start, length] -> an_array or nil
array[range] -> an_array or nil
array.slice(index) -> obj or nil
array.slice(start, length) -> an_array or nil
array.slice(range) -> an_array or nil
------------------------------------------------------------------------
Element Reference---Returns the element at index, or returns a
subarray starting at start and continuing for length elements, or
returns a subarray specified by range. Negative indices count
backward from the end of the array (-1 is the last element).
Returns nil if the index (or starting index) are out of range.
a = [ "a", "b", "c", "d", "e" ]
a[2] + a[0] + a[1] #=> "cab"
a[6] #=> nil
a[1, 2] #=> [ "b", "c" ]
a[1..3] #=> [ "b", "c", "d" ]
a[4..7] #=> [ "e" ]
a[6..10] #=> nil
a[-3, 3] #=> [ "c", "d", "e" ]
# special cases
a[5] #=> nil
a[6, 1] #=> nil
a[5, 1] #=> []
a[5..10] #=> []
其他提示
如果要分割/切割阵列上的索引i,
arr = arr.drop(i)
> arr = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
> arr.drop(2)
=> [3, 4, 5]
可以使用切片()以这样:
>> foo = [1,2,3,4,5,6]
=> [1, 2, 3, 4, 5, 6]
>> bar = [10,20,30,40,50,60]
=> [10, 20, 30, 40, 50, 60]
>> half = foo.length / 2
=> 3
>> foobar = foo.slice(0, half) + bar.slice(half, foo.length)
=> [1, 2, 3, 40, 50, 60]
顺便说一句,据我所知,Python的“名单”只是有效地实现动态增长的数组。插入在开始是在O(N),插入在所述端部摊销O(1),随机存取是O(1)。
另一种方法是使用范围方法
foo = [1,2,3,4,5,6]
bar = [10,20,30,40,50,60]
a = foo[0...3]
b = bar[3...6]
print a + b
=> [1, 2, 3, 40, 50 , 60]
我喜欢范围为这样:
def first_half(list)
list[0...(list.length / 2)]
end
def last_half(list)
list[(list.length / 2)..list.length]
end
然而,非常小心端点是否包含在你的范围内。这将成为你需要选择你要去的地方,打破中间的奇数长度的名单上是至关重要的。否则,你最终会重复计算中间元素。
在上面的例子将始终如一放中间元件中的最后一个的一半。
您也可以写像这样
foo = [1,2,3,4,5,6,7]
bar = [10,20,30,40,50,60,70]
half = foo.length / 2
foobar = (foo.first half) + (bar.drop half)
=> [1, 2, 3, 40, 50, 60, 70]
不隶属于 StackOverflow