This is my code and I'm not sure why this doesn't return the expected result: A Bunny Hops
text= "a bunny hops"
final = text.split.each{|i| i.capitalize}.join(' ')
puts final
Do as below using Array#map
:
text.split.map { |i| i.capitalize }.join(' ')
Corrected and short code :
text= "a bunny hops"
final = text.split.map(&:capitalize).join(' ')
puts final
# >> A Bunny Hops
Why didn't your one worked :
Because Array#each
method returns the receiver itself on which it has been called :
text= "a bunny hops"
text.split.each(&:capitalize) # => ["a", "bunny", "hops"]
But Array#map
returns a new array
text.split.map(&:capitalize) # => ["A", "Bunny", "Hops"]
I would do it as below using String#gsub
:
text= "a bunny hops"
text.gsub(/[A-Za-z']+/,&:capitalize) # => "A Bunny Hops"
Note: The pattern I used here with #gsub
, is not the trivial one. I did it as per the string have been given in the post itself. You need to change it as per the text string samples you will be having. But the above is a way to do such things with short code and more Rubyish way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With