Reputation: 2074
string = 'one a day'
how do I remove words from the string that are less than 2 characters?
result = 'one day'
Upvotes: 0
Views: 3170
Reputation: 2945
In order to remove not only English words, you should use \p{L}
'Comment ça va ?'.gsub(/\b\p{L}{1,2}\b/, '').squeeze(' ').strip
=> "Coment ?"
Upvotes: 0
Reputation: 334
i came independently to the same solution as the best answer, so here is a solution considering punctuation
string = 'one a day. One 1, 22 333 0. This days o! o'
p string.split(' ').reject{ |e| i = e.dup; i.gsub!(/\W/, ''); i.length == 1}.join(' ')
#==> "one day. One 22 333 This days"
Upvotes: 0
Reputation: 4271
This will get rid of 2 or 1 letter words and clean up white space.
str.gsub(/\b\w{1,2}\b/,"").gsub(/\s{2,}/," ").strip
Same thing with an array of values.
str = ["Dave is a dork", "a John is a name", "Shawn is a or Lindsey", "Shawn or Dave"]
str.map! { |str| str.gsub(/\b\w{1,2}\b/,"").gsub(/\s{2,}/," ").strip}
Upvotes: 1
Reputation: 230326
Break your string into individual words, filter out short ones, and then glue the string back together.
puts 'one a day'.split(' ').select{|w| w.length >= 2}.join(' ')
# => one day
Upvotes: 6
Reputation: 87396
Here's how you do it:
string = "on a boat"
result = string.split(' ').reject{|w| w.length < 2 }.join(' ') # => on boat
Upvotes: 0