【问题标题】:What is Enumerator object? (Created with String#gsub)什么是枚举器对象? (使用字符串#gsub 创建)
【发布时间】:2014-05-29 12:57:53
【问题描述】:

我有一个属性数组如下,

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

【问题讨论】:

    标签: ruby enumerator


    【解决方案1】:

    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> 
    

    【讨论】:

      【解决方案2】:

      当既没有提供块也没有提供第二个参数时,gsub 返回一个枚举器。查看here了解更多信息。

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

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

      或者

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

      希望这会有所帮助!

      【讨论】:

      • 注意#delete 它将删除给定字符串中的每个字符,而不是单词。例如"Photo of an otter".delete("Photo:") # =&gt; " f a er"
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-02
      • 1970-01-01
      相关资源
      最近更新 更多