有没有类似于Haskell循环的Ruby方法? Haskell 的循环接受一个列表并返回无限附加到自身的列表。它通常与 take 一起使用,它从数组的顶部抓取一定数量的元素。是否有一个 Ruby 方法接受一个数组并返回附加到自身的数组 n 次?
最佳答案
是的,它叫cycle
.来自文档:
Array.cycle (from ruby core) ------------------------------------------------------------------------------ ary.cycle(n=nil) {|obj| block } -> nil ary.cycle(n=nil) -> an_enumerator ------------------------------------------------------------------------------ Calls block for each element repeatedly n times or forever if none or nil is given. If a non-positive number is given or the array is empty, does nothing. Returns nil if the loop has finished without getting interrupted. If no block is given, an enumerator is returned instead. a = ["a", "b", "c"] a.cycle {|x| puts x } # print, a, b, c, a, b, c,.. forever. a.cycle(2) {|x| puts x } # print, a, b, c, a, b, c.
Edit:
It seems like whats inside the block is basically a "Lambda", and as far as I know, I can't make a lambda concat each element onto an existing array.
b = [1, 2, 3]
z = []
b.cycle(2) { |i| z << i }
z # => [1, 2, 3, 1, 2, 3]
关于类似于 Haskells 循环的 Ruby 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15240840/