简体   繁体   中英

Ruby Method similar to Haskells cycle

Is there a Ruby method similar to Haskell's cycle? Haskell's cycle takes a list and returns that list infinitely appended to itself. It's commonly used with take which grabs a certain number of elements off the top of an array. Is there a Ruby method that takes an array and returns the array appended to itself some n number of times?

Yes, it's called cycle . From the documentation:

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]

You can multiply an array by an integer using Array#* :

ary * int → new_ary

[...] Otherwise, returns a new array built by concatenating the int copies of self .

So you can do things like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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