我有一个属性数组如下,
attributes = ["test, 2011", "photo", "198.1 x 198.1 cm", "Photo: Manu PK Full Screen"]
Run Code Online (Sandbox Code Playgroud)
当我这样做时,
artist = attributes[-1].gsub("Photo:")
p artist
Run Code Online (Sandbox Code Playgroud)
我在终端获得以下输出
#<Enumerator: "Photo: Manu PK Full Screen":gsub("Photo:")>
Run Code Online (Sandbox Code Playgroud)
想知道为什么我得到一个枚举器对象作为输出?提前致谢.
编辑:请注意,而不是attributes[-1].gsub("Photo:", ""), I am doing attributes[-1].gsub("Photo:")那么想知道为什么枚举器对象已经返回(我期待一个错误消息)和发生了什么.
Ruby - 1.9.2
Rails - 3.0.7
sar*_*old 16
一个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
Run Code Online (Sandbox Code Playgroud)
在前三种情况下,替换可以立即进行,并返回一个新字符串.但是,如果您没有提供替换字符串,替换哈希或替换块,则会返回该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>
Run Code Online (Sandbox Code Playgroud)
当既没有提供块也没有提供第二个参数时,gsub返回一个枚举器.看看这里获取更多信息.
要删除它,您需要第二个参数.
attributes[-1].gsub("Photo:", "")
Run Code Online (Sandbox Code Playgroud)
要么
attributes[-1].delete("Photo:")
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!!