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
2009-11-17 00:21:08
here's a destructive (in-place) example: `array.each {|word| word.delete!('aeiou')}`
glenn jackman
2009-11-17 01:00:38
here's another destructive (in-place) example: `array.map! {|word| word.gsub(keyword,'')}`
glenn mcdonald
2009-11-17 01:13:58
we are the destructoglenns
glenn mcdonald
2009-11-17 01:14:34
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
2009-11-17 00:21:25