我有一个产生字符串的Enumerator::Generator
实例。我需要将它们连接成一个字符串。
什么是这样做的好方法?我注意到*
不起作用。我知道我可以先.map {|x| x}
,但这似乎很不习惯
[我认为在这种情况下,我可以使用inject
运算符来获取reduce
/ 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