获取(保留)数组中的前 n 个元素并删除其余元素的好方法是什么?
如果没有内置方法,则
def take! ary, n
...
end
z = (1..10).to_a
take! z, 5
# z is [1,2,3,4,5]
最佳答案
有几种可能性。
总是有效的瑞士军刀是Array#replace
它只是用参数的内容替换接收器的内容,因此可用于将任何数组转换为任何其他数组,因此您可以这样说:
class Array
def take!(n)
replace(take(n))
end
end
使用 Array#slice!
是另一种可能性:
class Array
def take!(n)
slice!(0, n)
end
end
关于arrays - 拿怎么办!在 ruby ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36295813/