ruby - How to adapt usual method into method of the Class? -


need beginner(training purpose). example, have method custom_uniq , want work standard .uniq ([1, 2, 1, 3, 3].uniq >> [1,2,3])

def custom_uniq(arr) new_arr = []   arr.each |elem|     new_arr << elem if new_arr.include?(elem) == false   end new_arr end 

so, particular part should modify insert working method right 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] 

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

or, @toro2k suggested, make use of enumerable#each_with_object method:

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

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -