7

In Python i can slice array with "jump-step". Example:

In [1]: a = [1,2,3,4,5,6,7,8,9] 

In [4]: a[1:7:2] # start from index = 1 to index < 7, with step = 2
Out[4]: [2, 4, 6]

Can Ruby do it?

4

3 回答 3

7
a = [1,2,3,4,5,6,7,8,9]
a.values_at(*(1...7).step(2)) - [nil]
#=> [2, 4, 6] 

尽管在上述情况下,该- [nil]部分不是必需的,但它仅在您的范围超出数组大小的情况下起作用,否则您可能会得到如下结果:

a = [1,2,3,4,5,6,7,8,9]
a.values_at(*(1..23).step(2))
#=> [2, 4, 6, 8, nil, nil, nil, nil, nil, nil, nil, nil]
于 2013-04-26T08:58:10.263 回答
3

在 ruby​​ 中,要获得相同的输出:

a = [1,2,3,4,5,6,7,8,9]
(1...7).step(2).map { |i| a[i] }
=> [2, 4, 6] 
于 2013-04-26T09:20:34.473 回答
2

如果你真的错过了 Python 切片步骤语法,你可以让 Ruby 做一些非常相似的事情。

class Array
  alias_method :brackets, :[]

  def [](*args)
    return brackets(*args) if args.length != 3
    start, stop, step = *args
    self.values_at(*(start...stop).step(step))
  end
end

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr[1,7,2]
#=> [2, 4, 6]
于 2013-04-26T12:01:44.460 回答