簡體   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