tags:

views:

73

answers:

2

How can i remove a repeating string keyword from all elements in an array ?

+5  A: 

I think you mean you have an array of strings and they all contain some substring that you want to remove. Non-destructively:

array.map {|s| s.gsub(keyword, '')}

Use destructive variants as desired to do it in-place.

Chuck
here's a destructive (in-place) example: `array.each {|word| word.delete!('aeiou')}`
glenn jackman
here's another destructive (in-place) example: `array.map! {|word| word.gsub(keyword,'')}`
glenn mcdonald
we are the destructoglenns
glenn mcdonald
A: 

Are you referring to string in the array, or non-unique elements. For the first, use the uniq method:

p ["foo", "bar", "foo", "baz"].uniq
["foo", "bar", "baz"]

For the latter, try something like:

p ["foo", "bar", "foo", "baz"].map { |x| x.gsub('oo', '') }
["f", "bar", "f", "baz"]
brianegge