繁体   English   中英

Ruby方法类似于Haskells循环

[英]Ruby Method similar to Haskells cycle

是否有类似于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.

编辑:

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

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

您可以使用Array#*将数组乘以整数:

ary * int→new_ary

[...]否则,返回通过连接selfint副本构建的新数组。

所以你可以做这样的事情:

>> [1, 2] * 3
=> [1, 2, 1, 2, 1, 2]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM