How to split a string into words in Ruby

2 Answers

0 votes
def split_string(s, delims)
  re = Regexp.new(delims)

  parts = s.split(re)

  parts.reject(&:empty?)
end

s = '-c, c++.. c#:: -java ,php...python      ruby'
delims = "[ ,.:\\-!]+"

tokens = split_string(s, delims)

tokens.each do |t|
  puts t
end



# run:
#
# c
# c++
# c#
# java
# php
# python
# ruby
# 

 



answered Aug 29 by avibootz
edited Aug 29 by avibootz
0 votes
def split_string(s, delims)
  delim_set = delims.chars.to_set

  normalized = s.chars.map { |ch| delim_set.include?(ch) ? " " : ch }.join

  normalized.split(" ").reject(&:empty?)
end

require "set"

s = "-c, c++.. c#:: -java! ,php...python:      go!"
delims = " ,.:\\-!"

tokens = split_string(s, delims)

tokens.each { |t| puts t }



# run:
#
# c
# c++
# c#
# java
# php
# python
# go
# 

 



answered Aug 29 by avibootz
...