2011-12-13 78 views
6

我有一个属性阵列如下,什么是枚举器对象? (创建与字符串#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:")> 

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

编辑: 请注意,而不是attributes[-1].gsub("Photo:", ""), I am doing attributes[-1].gsub("Photo:")所以想知道为什么枚举器对象已经在这里返回(我期待一个错误消息)以及发生了什么。

红宝石 - 1.9.2

导轨 - 3.0.7

回答

16

Enumerator对象提供了一些常见的枚举方法 - nexteacheach_with_indexrewind

你得到这里的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> 
5

当既不是块,也不是第二个参数被提供,GSUB返回的枚举器。查看here了解更多信息。

要删除它,您需要第二个参数。

attributes[-1].gsub("Photo:", "") 

或者

attributes[-1].delete("Photo:") 

希望这有助于!