oprogfrogo
oprogfrogo

Reputation: 2074

Ruby - Remove short words from the string

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

Answers (6)

Aray Karjauv
Aray Karjauv

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 ?"

Demo

Upvotes: 0

thebugfinder
thebugfinder

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

Alexey
Alexey

Reputation: 9447

"once a day".gsub(/\b\w\b/, "").gsub(/\s+/, "")
# => "once day"

Upvotes: 0

slindsey3000
slindsey3000

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

Sergio Tulentsev
Sergio Tulentsev

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

David Grayson
David Grayson

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

Related Questions