将红宝石枚举符加入字符串

问题描述 投票:0回答:2

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

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

ruby generator enumerator
2个回答
1
投票

[我认为在这种情况下,我可以使用inject运算符来获取reduce / reduce(对于同一方法的别名,对我来说,reduce的名称更有意义):

+

作为完整示例:

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

1
投票
# 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
© www.soinside.com 2019 - 2024. All rights reserved.