Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to count the words of a string in ruby

Tags:

ruby

I want to do something like this

def get_count(string)
 sentence.split(' ').count
end

I think there's might be a better way, string may have built-in method to do this.

like image 327
mko Avatar asked Jan 20 '23 10:01

mko


1 Answers

I believe count is a function so you probably want to use length.

def get_count(string) 
    sentence.split(' ').length
end

Edit: If your string is really long creating an array from it with any splitting will need more memory so here's a faster way:

def get_count(string) 
    (0..(string.length-1)).inject(1){|m,e| m += string[e].chr == ' ' ? 1 : 0 }
end
like image 198
Candide Avatar answered Jan 29 '23 21:01

Candide