如何在Ruby中返回一个数组的一部分?
用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在数组中做了所有事情,我不知道是否有类似的东西。
是的,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[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]
你可以使用slice()来做到这一点:
>> 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“列表”只是有效地实现了dynamic增长的数组。 插入开始处在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]
你也可以写这样的东西
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]