I want to only delete a[0]. Any simple, clean way of doing this?
With no thought to efficiency, here is my effort:
class Array
Returns new array with unmatched elements removed
“matchiness” is determined by comparing elements
returned by the block or the elements themselves if
no block is provided
def strip_unmatched
classifed = inject(Hash.new{|h,k| h[k] = []}) do |collector, item|
key = block_given? ? yield(item) : item
collector[key] << item
collector
end
classifed.reject {|k,v| v.size == 1}.values.flatten
end
Modifies self by removing elements that don’t match
other elements. see #strip_unmatched.
def strip_unmatched!(&blk)
replace(strip_unmatched(&blk))
end
end
a = [‘12345 keep’, ‘12345 keep 2’, ‘11111 i should be deleted’,
‘99393 delete me too’, ‘22233 keep’, ‘22233 keep me as well’,
‘78444 getting deleted’]
new_a = a.strip_unmatched { |i| i[0…4] }
puts “STRIPPED: #{new_a.inspect}”
puts “ORIGINAL: #{a.inspect}”
try version that modifies receiver
a.strip_unmatched!{|i| i[0…4] }
puts “ORIGINAL: #{a.inspect}”
$ jruby strip_mismatches.rb
STRIPPED: [“12345 keep”, “12345 keep 2”, “22233 keep”, “22233 keep me as
well”]
ORIGINAL: [“12345 keep”, “12345 keep 2”, “11111 i should be deleted”,
“99393
delete me too”, “22233 keep”, “22233 keep me as well”, “78444 getting
deleted”]
ORIGINAL: [“12345 keep”, “12345 keep 2”, “22233 keep”, “22233 keep me as
well”]