加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 什么是Enumerator对象? (使用String#gsub创建)

发布时间:2020-12-16 21:17:33 所属栏目:百科 来源:网络整理
导读:我有一个属性数组如下, 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("Phot
我有一个属性数组如下,
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:")>

想知道为什么我得到一个枚举器对象作为输出?提前致谢.

编辑:
请注意,而不是属性[-1] .gsub(“Photo:”,“”),我正在做属性[-1] .gsub(“Photo:”)所以想知道为什么枚举器对象已经返回(我期待一条错误信息)以及发生了什么.

Ruby – 1.9.2

Rails – 3.0.7

解决方法

Enumerator对象提供了枚举常用的一些方法 – next,each,each_with_index,rewind等.

你在这里获得了Enumerator对象,因为gsub非常灵活:

gsub(pattern,replacement) → new_str
gsub(pattern,hash) → new_str
gsub(pattern) {|match| block } → new_str
gsub(pattern) → enumerator

在前三种情况下,替换可以立即进行,并返回一个新字符串.但是,如果您不提供替换字符串,替换哈希或替换块,则会返回Enumerator对象,该对象允许您访问匹配的字符串片段以便以后使用:

irb(main):022:0> s="one two three four one"
=> "one two three four one"
irb(main):023:0> enum = s.gsub("one")
=> #<Enumerable::Enumerator:0x7f39a4754ab0>
irb(main):024:0> enum.each_with_index {|e,i| puts "#{i}: #{e}"}
0: one
1: one
=> " two three four "
irb(main):025:0>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读