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.
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.
On Wed, Jun 6, 2012 at 10:28 PM, ideal one [email protected] 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.
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.
“Jesús Gabriel y Galán” [email protected] 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.
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.
回答的真是精彩!
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs