【问题标题】:Monkey Patching Arrays in RubyRuby 中的 Monkey 修补数组
【发布时间】:2016-02-15 08:15:11
【问题描述】:

我将自己的方法添加到 Array 类中,该方法与 Array#uniq 执行相同的操作。

这是我的版本:

arr = ["fun", "sun", 3, 5, 5, 5, 1, 2, 1, "fun"]

class Array
    def my_uniq
        new_arr = []
        each do |item|
            new_arr << item unless new_arr.include?(item)
        end
        new_arr
    end
end

print arr.my_uniq

有没有办法修改它以返回唯一元素的索引而不是元素本身?

【问题讨论】:

  • 我建议您编辑您的问题。 1. 您对my_uniq 的方法定义无关紧要,因此将其删除(对不起。) 2. 将第二句替换为更精确的内容,例如“如何编写返回(最小)索引的Array 方法数组的每个唯一元素?” (不需要粗体字。) 3. 删除你的第三句。 (可悲的是,没有人在乎。)。 4. 举一个例子,保留您的输入 (arr = ["fun",...]) 并提供您想要或预期的输出([0, 1, 2, 3, 6, 7],如果我的理解是正确的)。
  • 当你给出一个例子时,为每个输入分配一个变量是有帮助的,就像你所做的那样 (arr = ....)。这样,读者可以在答案和 cmets 中引用这些变量,而无需定义它们。最后,Ruby 约定是使用 snake_case 作为变量和方法的名称(例如,new_arr 而不是 newArr)。您不必这样做,但如果您不这样做,请注意,您的代码的读者可能会认为您是新手。
  • 感谢您的提示。我会更新并阅读 Ruby 风格。
  • 再想一想,请忽略我的建议#1;只需明确说明这是您的 Array#uniq 代码,并且您正在尝试修改它以返回唯一元素的索引数组。
  • 关于您的修订的另一个建议:将您的第二句话移到代码后面,然后说“有没有办法修改它以返回唯一元素的索引而不是元素本身?对于arr 的给定值,我希望它返回数组[0, 1, 2, 3, 6, 7]"。一旦你看到它,我会删除这个评论。无需回复。

标签: arrays ruby monkeypatching


【解决方案1】:

each_with_index 将允许您迭代数组并返回索引。

each_with_index do |item, index|
  newArr << index unless newArr.include?(item)
end

【讨论】:

    【解决方案2】:
    class Array
      def indices_uniq
        uniq.map { |e| index(e) }
      end
    end
    
    arr = ["fun", "sun", 3, 5, 5, 5, 1, 2, 1, "fun"]
    arr.indices_uniq
      #=> [0, 1, 2, 3, 6, 7] 
    

    要看看这里发生了什么,让我们写得更详细一些,并包含一些代码来显示中间值:

    class Array
      def indices_uniq
        puts "self = #{self}"
        arr = self
        u = arr.uniq
        puts "u = #{u}"
        u.map { |e|
          puts "#{e} is at index #{index(e)}"
          arr.index(e) }
      end
    end
    
    arr.indices_uniq
      # self = ["fun", "sun", 3, 5, 5, 5, 1, 2, 1, "fun"]
      # u = ["fun", "sun", 3, 5, 1, 2]
      # fun is at index 0
      # sun is at index 1
      # 3 is at index 2
      # 5 is at index 3
      # 1 is at index 6
      # 2 is at index 7
      #=> [0, 1, 2, 3, 6, 7] 
    

    我们可以替换掉uarr

    class Array
      def indices_uniq
        self.uniq.map { |e| self.index(e) }
      end
    end
    
    arr.indices_uniq
       #=> [0, 1, 2, 3, 6, 7]
    

    关键:self 是没有显式接收器的方法的接收器。 在方法的最后一个版本中,uniqinclude 都具有显式接收器 self .由此可见,如果显式接收者被移除,接收者仍然是self

    class Array
      def indices_uniq
        uniq.map { |e| index(e) }
      end
    end
    
    arr.indices_uniq
       #=> [0, 1, 2, 3, 6, 7]
    

    另一种方法是将操作线更改为:

    map { |e| index(e) }.uniq
    

    【讨论】:

      猜你喜欢
      • 2011-03-27
      • 2011-12-15
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 2017-04-29
      • 1970-01-01
      • 2014-03-03
      • 1970-01-01
      相关资源
      最近更新 更多