什么是枚举器对象? (使用 String#gsub 创建)
我有一个属性数组,如下所示,
attributes = ["test, 2011", "photo", "198.1 x 198.1 cm", "Photo: Manu PK Full Screen"]
当我这样做时,
artist = attributes[-1].gsub("Photo:")
p artist
我在终端中得到以下输出
#<Enumerator: "Photo: Manu PK Full Screen":gsub("Photo:")>
想知道为什么我会得到一个枚举器对象作为输出?提前致谢。
编辑: 请注意,我正在执行 attribute[-1].gsub("Photo:"),而不是 attributes[-1].gsub("Photo:", "")
所以想知道为什么枚举器对象返回这里(我期待一条错误消息)以及发生了什么?
红宝石 - 1.9.2
Rails - 3.0.7
I have an attributes array as follows,
attributes = ["test, 2011", "photo", "198.1 x 198.1 cm", "Photo: Manu PK Full Screen"]
When i do this,
artist = attributes[-1].gsub("Photo:")
p artist
i get the following output in terminal
#<Enumerator: "Photo: Manu PK Full Screen":gsub("Photo:")>
Wondering why am I getting an enumerator object as output? Thanks in advance.
EDIT:
Please note that instead of attributes[-1].gsub("Photo:", ""), I am doing attributes[-1].gsub("Photo:")
So would like to know why enumerator object has returned here( I was expecting an error message) and what is going on.?
Ruby - 1.9.2
Rails - 3.0.7
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Enumerator
对象提供了一些方法常见的枚举 -next
、each
、each_with_index
、rewind
等。您将得到
Enumerator
对象在这里因为gsub
非常灵活:在前三种情况下,替换可以立即进行,并返回一个新字符串。但是,如果您不提供替换字符串、替换哈希或替换块,您将返回
Enumerator
对象,该对象可让您获取字符串的匹配部分以便稍后使用:An
Enumerator
object provides some methods common to enumerations --next
,each
,each_with_index
,rewind
, etc.You're getting the
Enumerator
object here becausegsub
is extremely flexible:In the first three cases, the substitution can take place immediately, and return a new string. But, if you don't give a replacement string, a replacement hash, or a block for replacements, you get back the
Enumerator
object that lets you get to the matched pieces of the string to work with later:当既没有提供块也没有提供第二个参数时,gsub 返回一个枚举器。请参阅此处了解更多信息。
要删除它,您需要第二个参数。
或者
希望这有帮助!
When neither a block nor a second argument is supplied, gsub returns an enumerator. Look here for more info.
To remove it, you need a second parameter.
Or
Hope this helps!!