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



我有一个生成字符串的Enumerator::Generator实例。我需要把它们连成一根绳子。

做这件事的好方法是什么?我注意到*不起作用。我知道我可以先.map {|x| x},但这似乎不太习惯

我认为在这种情况下,我可能会使用+运算符来获取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 "
a=["Raja","gopalan"].to_enum #let's assume this is your enumerator

编写以下代码

p a.map(&:itself).join

p a.to_a.join

输出

"Rajagopalan"

最新更新