ruby - Why am I having trouble creating a custom array method that returns a hash with indices of matching array values? -
i'm trying monkey patch array class method that, when passed [1, 3, 4, 3, 0, 3, 1]
, return hash { 1 => [0, 6], 3 => [1, 3, 5] }
, key number matching to, , value array indices of matches.
here's code have far. can't tell why it's returning {1=>[0, 2, 3, 1, 2, 0], 3=>[0, 2, 3, 1, 2, 0], 0=>[0, 2, 3, 1, 2, 0]}
:
class array def dups matches = {} matches_index = [] self.each |i| self[(i_index + 1)..-1].each_with_index |j, j_index| matches_index << j_index if self[i] == self[j] end matches[i] = matches_index end matches.keep_if { |key, value| value.length > 1 } end end
to improve on stas s excellent solution:
class array def dups (self.each_index.group_by {|i| self[i]}).keep_if{|k, v| v.size > 1} end end
which results in array of only duplicates.
Comments
Post a Comment