将 ruby 枚举器连接到字符串中

Join a ruby enumerator into a string

我有一个生成字符串的 Enumerator::Generator 实例。我需要将它们连接成一个字符串。

这样做的好方法是什么?我注意到 * 不起作用。我知道我可以先 .map {|x| x} 但这似乎很不合常理

a=["Raja","gopalan"].to_enum #let's assume this is your enumerator

编写如下代码

p a.map(&:itself).join

p a.to_a.join

输出

"Rajagopalan"

我认为在这种情况下,我可能会使用 inject/reduce(相同方法的别名,reduce 作为名称对我来说更有意义) + 运算符:

enum.reduce(:+)
# or, passing in a block
enum.reduce(&:+)

作为一个完整的例子:

# never used Enumerator::Generator directly, but you called it out specifically
# in your question, and this seems to be doing the trick to get it working
enum = Enumerator::Generator.new do |y|
  y.yield "ant"
  y.yield "bear"
  y.yield "cat"
end

p enum.reduce(&:+) # output: "antbearcat"
# crude example of modifying the strings as you join them
p enum.reduce('') { |memo, word| memo += word.upcase + ' ' }
# output: "ANT BEAR CAT "