lundi 7 janvier 2019

Split string by multiple consecutive delimiters on ruby.

I want to split a string by whitespaces, , and . using ruby commands. word.split(" ") will split by white spaces; word.split(",") will split by ,; word.split(".") will split by . How to do all three at once?

puts "Enter string "
text=gets.chomp
frequencies=Hash.new(0)
delimiters = [',', ' ', "."]
words = text.split(Regexp.union(delimiters))
words.each { |word| frequencies[word] +=1}
frequencies=frequencies.sort_by {|a,b| b}
frequencies.reverse!
frequencies.each { |wor,freq| puts "#{wor} #{freq}"}


Current (wrong) Output
Enter string 
hello this is a hello, allright this is a hello.

hello 3
a 2
is 2
this 2
allright 1
 1


I donot want the last line of the output. It considers the space as a 
word too. This may be because there were consecutive delimiters (, & " 
") . How to solve this issue

Expected Output

Enter string 
hello this is a hello, allright this is a hello.


hello 3
a 2
is 2
this 2
allright 1

Aucun commentaire:

Enregistrer un commentaire