2011-12-13 81 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:") 

希望這有助於!