What's the Ruby equivalent of Python `itertools.chain`?

what'd
what w
what does
how to pronounce what
what is called
what's
what is love
what means sign

Python's itertools module provides a lots of goodies with respect to processing an iterable/iterator by use of generators. What's the Ruby equivalent of Python itertools.chain?

I am not a Ruby programmer, but I think something like this should do it:

def chain(*iterables)
   for it in iterables
       if it.instance_of? String
           it.split("").each do |i|
               yield i
           end
       else
           for elem in it
               yield elem
           end
       end
   end
end

chain([1, 2, 3], [4, 5, 6, [7, 8, 9]], 'abc') do |x|
    print x
    puts
end

Output:

1
2
3
4
5
6
[7, 8, 9]
a
b
c

If you don't want to flatten strings, then using Array#flatten this can be shortened to:

def chain(*iterables)
    return iterables.flatten(1) # not an iterator though
end
print chain([1, 2, 3], [4, 5, 6, [7, 8, 9]], 'abc')
#[1, 2, 3, 4, 5, 6, [7, 8, 9], "abc"]

What, what definition: 1. used to ask for information about people or things: 2. used in questions that show you are…. Learn more. Quickly send and receive WhatsApp messages right from your computer.

The Ruby equivalent of a Python iterator is an Enumerator. There is no method for chaining two Enumerators, but one can easily be written like so:

class Enumerator
  def chain(*others)
    self.class.new do |y|
      [clone, *others.map(&:clone)].each do |e|
        loop do y << e.next end
      end
    end
  end

  def +(other)
    chain(other)
  end
end

e1 = %w[one two].each
e2 = %w[three four].each
e3 = %w[five six].each

e = e1.chain(e2, e3)

e.map(&:upcase)
# => ['ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX']

what, Usage Note: When what is the subject of a clause, it takes a singular verb if the word or phrase that completes the sentence (the complement) is singular, as in I � What definition, (used interrogatively as a request for specific information): What is the matter? See more.

From the Python docs for itertools.chain:

Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.

First, an example in Python

from itertools import chain

# nested arrays
iterables = [
                ["one", "two"], 
                ["three", "four"], 
                ["five", "six", "6", ["eight", "nine", "ten"]]
            ]

list(chain(*iterables))

Output:

['one', 'two', 'three', 'four', 'five', 'six', '6', ['eight', 'nine', 'ten']]

I am learning Ruby, so I tried to replicate the behavior using the code example from the Python docs:

# taken from Python docs as a guide
def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element  # NOTE! `yield` in Python is not `yield` in Ruby. 
            # for simplicity's sake think of this `yield` as `return`

My Ruby code:

def chain(*iterables)
  items = []
  iterables.each do |it|
    it.each do |item|
      items << item
     end
  end
  items
end

nested_iterables = [%w[one two], %w[three four], %W[five six #{3 * 2}]]
nested_iterables[2].insert(-1, %w[eight nine ten])

puts chain(*nested_iterables)  

# and to enumerate
chain(*nested_iterables).each do |it|
  puts it
end

Both output:

["one", "two", "three", "four", "five", "six", "6", ["eight", "nine", "ten"]]

WHAT, B) A phrase that seems to simply state the obvious but actually means "it will be what it is," as Duration: 48:27 Posted: Jan 7, 2016 what definition: 1. used to ask for information about people or things: 2. used in questions that show you are…. Learn more.

Code

def chain(*aaa)
  aaa.each { |aa| (aa.class == String ? aa.split(//) : aa).each { |a| yield a } }
end

Example

chain([0, 1], (2..3), [[4, 5]], {6 => 7, 8 => 9}, 'abc') { |e| print e, ',' }

Output

0,1,2,3,[4, 5],[6, 7],[8, 9],a,b,c,

What, These transitions often bring a mix of anticipation and excitement — a sense of not knowing exactly what lies ahead but an eagerness to get� whatever: adverb at all , of any description , of any kind or sort , whatsoever , whichever

Since Ruby 2.6 Enumerables have a chain method. It does not split up strings in characters.

It is what it is, Three common work practices can help us decide what to continue doing — and what to ditch. Have an overarching mission or purpose. Set� Desperate to secure funding for her med tech startup, an idealistic scientist and her husband strike an outrageous deal with a mysterious investor. Watch trailers & learn more.

Anxious About What's Next? Here's How to Cope., An international effort to update the definition of what museums are has been met with resignations and political intrigue. The ORIGINAL and OFFICIAL "What What (In the Butt)" video! Samwell will CALL your friends and family! Go here: http://officialsamwell.com/live-call/ This is

What's Your Family's Mission Statement?, WhatsApp Messenger: More than 2 billion people in over 180 countries use WhatsApp to stay in touch with friends and family, anytime and anywhere. WhatsApp is free and offers simple, secure, reliable messaging and calling, available on phones all over the world.

What Is a Museum? A Dispute Erupts Over a New Definition, Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for.

Comments
  • You might want to explain what itertools.chain does - not every Ruby expert knows Python.
  • @FrankSchmitt It produces an iterator that sequentially chains two or more existing iterators, i.e. produces values from one iterator until its exhaustion, then from the other, and so on.