2

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?

dreftymac
  • 31,404
  • 26
  • 119
  • 182
  • 1
    Possible duplicate of [What's the Ruby equivalent of Python \`itertools.chain\`?](https://stackoverflow.com/questions/27919677/whats-the-ruby-equivalent-of-python-itertools-chain) – zvone Mar 24 '19 at 20:16
  • Are you referring to `itertools.chain`? That operates on iterables; using it on dictionaries is kind of... weird. – Aran-Fey Mar 24 '19 at 20:17

3 Answers3

3

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
steenslag
  • 79,051
  • 16
  • 138
  • 171
0

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}
alexts
  • 180
  • 2
  • 13
0

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

Enumerator::Chain.new(data_chained, data2)