Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby string split on more than one character

Tags:

string

split

ruby

I have a string, say "Hello_World I am Learning,Ruby". I would like to split this string into each distinct word, what's the best way?

Thanks! C.

like image 261
curious Avatar asked Aug 20 '26 17:08

curious


2 Answers

You could use \W for any non-word character:

"Hello_World I am Learning,Ruby".split /[\W_]/
=> ["Hello", "World", "I", "am", "Learning", "Ruby"]

"Hello_World I am Learning,   Ruby".split /[\W_]+/
=> ["Hello", "World", "I", "am", "Learning", "Ruby"]
like image 90
Samnang Avatar answered Aug 22 '26 08:08

Samnang


You can use String.split with a regex pattern as the parameter. Like this:

"Hello_World I am Learning,Ruby".split /[ _,.!?]/
=> ["Hello", "World", "I", "am", "Learning", "Ruby"]
like image 21
Zoltán Szőcs Avatar answered Aug 22 '26 08:08

Zoltán Szőcs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!