Is there anything better than string.scan(/(\w|-)+/).size
(the -
is so, e.g., "one-way street" counts as 2 words instead of 3)?
views:
151answers:
2
A:
If the 'word' in this case can be described as an alphanumeric sequence which can include '-' then the following solution may be appropriate (assuming that everything that doesn't match the 'word' pattern is a separator):
>> 'one-way street'.split(/[^-a-zA-Z]/).size
=> 2
>> 'one-way street'.split(/[^-a-zA-Z]/).each { |m| puts m }
one-way
street
=> ["one-way", "street"]
However, there are some other symbols that can be included in the regex - for example, ' to support the words like "it's".
Kirill Ishanov
2009-09-16 08:46:12