String character count

Hi,
Following is my input:-
Str = "This is a String."

expected output is :-
output = "4 2 1 7"

I tried doing this but was not successful, any thoughts pls

puts Str.count(" ").size -> This doesn't fit my expected output.

···

--
Posted via http://www.ruby-forum.com/.

You can split with Str.split(" "), which will return an array of strings.
Iterate through the array counting the length of the individual
strings, then join the resulting numbers using Array#join:

1.9.2p290 :001 > s = "this is a string."
=> "this is a string."
1.9.2p290 :002 > s.split(" ").map {|x| x.length}.join(" ")
=> "4 2 1 7"

Jesus.

···

On Wed, Jun 6, 2012 at 10:28 PM, ideal one <lists@ruby-forum.com> wrote:

Hi,
Following is my input:-
Str = "This is a String."

expected output is :-
output = "4 2 1 7"

I tried doing this but was not successful, any thoughts pls

puts Str.count(" ").size -> This doesn't fit my expected output.

"Jesús Gabriel y Galán" <jgabrielygalan@gmail.com> wrote in post
#1063418:

1.9.2p290 :001 > s = "this is a string."
=> "this is a string."
1.9.2p290 :002 > s.split(" ").map {|x| x.length}.join(" ")
=> "4 2 1 7"

Or shorter:

s.split.map(&:length).join ' '

Or even shorter and more robust (will handle any sequence of any space
characters):

s.gsub /\S+/, &:length

However, this is also slower.

···

--
Posted via http://www.ruby-forum.com/\.

Jan E. wrote in post #1063505:

s.split.map(&:length).join ' '

Or even shorter and more robust (will handle any sequence of any space
characters):

s.gsub /\S+/, &:length

However, this is also slower.

回答的真是精彩!

···

--
Posted via http://www.ruby-forum.com/\.