简体   繁体   English

Ruby等同于Python chain()

[英]Ruby equivalent to Python chain()

What is the Ruby equivalent of the chain iterator in python? 什么是python中的链迭代器的Ruby等价物?

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

How can this be done in Ruby? 如何在Ruby中完成?

Since Ruby 2.6: if it is Enumerable, you can chain it: (example from the docs, chaining a Range to an Array) 由于红宝石2.6:如果它是可枚举,可以连锁 (从文档例如,链接一个Range到数组):它

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

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}

I misunderstood the issue, it may be the same as itertools.chain in python. 我误解了这个问题,它可能与python中的itertools.chain相同。 This worked for me -> 这对我有用->

Enumerator::Chain.new(data_chained, data2) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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