Ruby方法类似于Haskells循环

Jos*_*sto 2 ruby haskell functional-programming

是否有类似于Haskell循环的Ruby方法?Haskell的循环获取一个列表并返回无限附加到其自身的列表.它通常与take一起使用,它从数组的顶部抓取一定数量的元素.是否有一个Ruby方法接受一个数组并返回附​​加到自身的数组n次?

the*_*Man 9

是的,它被称为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.

编辑:

看起来块中的内容基本上是"Lambda",据我所知,我不能将lambda concat每个元素连接到现有数组上.

b = [1, 2, 3]
z = []
b.cycle(2) { |i| z << i }
z # => [1, 2, 3, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

  • 神奇的事情发生了 神秘的方法似乎从未出现过.:-) (3认同)