如何将常用方法转化为类的方法?

时间:2013-07-31 11:39:17

标签: ruby

需要初学者帮助(培训目的)。例如,我有方法custom_uniq,并希望它像标准.uniq([1,2,1,3,3] .uniq>> [1,2,3])

一样工作
def custom_uniq(arr)
new_arr = []
  arr.each do |elem|
    new_arr << elem if new_arr.include?(elem) == false
  end
new_arr
end

那么,我应该修改哪些特定部分才能将工作方法直接插入Class?

class Array
  def custom_uniq
   ?????????
   ????????
  end
end
arr = [1,2,3,1,3,4,5,77]
arr.custom_uniq >> [1,2,3,4,5,77]

2 个答案:

答案 0 :(得分:3)

这是Array#Reject的完美用例和对所见项目的记忆:

class Array
  def custom_uniq
    seen = Hash.new
    reject do |item|
      item_is_duplicate = seen[item] # Check if item has occured already
      seen[item] = true unless item_is_duplicate # Remember seeing new item
      item_is_duplicate # Reject the item from returned array if duplicate
    end
  end
end

编辑:关于RUNTIMES的MISC状况......

我制作了以下图表来演示使用基于散列的方法(如此)和每次迭代检查输出数组之间的区别:

gnuplot

用于生成此图的代码(包含定义片段的43行)为here

答案 1 :(得分:2)

class Array
  def custom_uniq
    new_array = []
    each do |elem| # you call each method on self here
      new_array << elem unless new_array.include?(elem)
    end
    new_array
  end
end

或者,正如@ toro2k建议的那样,您可以使用Enumerable#each_with_object方法:

class Array
  def custom_uniq
    each_with_object([]) do |elem, new_array|
      new_array << elem unless new_array.include? elem
    end
  end
end