Ruby equivalent to Python chain()

99 Views Asked by At

What is the Ruby equivalent of the chain iterator in python?

data_chained = []
data2 = {}     
data_chained = chain(data_chained, data2)

How can this be done in Ruby?

3

There are 3 best solutions below

0
steenslag On BEST ANSWER

Since Ruby 2.6: if it is Enumerable, you can chain it: (example from the docs, chaining a Range to an Array)

e = Enumerator::Chain.new(1..3, [4, 5]) 
e.to_a #=> [1, 2, 3, 4, 5]
e.size #=> 5
0
alexts On

Is this what you are looking for?

Hash#merge

You use it like below:

h1 = { "a" => 100, "b" => 200 }
h2 = { "b" => 254, "c" => 300 }
h1.merge(h2)   #=> {"a"=>100, "b"=>254, "c"=>300}
h1.merge(h2){|key, oldval, newval| newval - oldval}
       #=> {"a"=>100, "b"=>54,  "c"=>300}
h1             #=> {"a"=>100, "b"=>200}
0
Ashima Sood On

I misunderstood the issue, it may be the same as itertools.chain in python. This worked for me ->

Enumerator::Chain.new(data_chained, data2)