Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalize the first letter of each word - Ruby

Tags:

ruby

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
like image 279
Ken Avatar asked Dec 11 '22 08:12

Ken


1 Answers

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.

like image 169
Arup Rakshit Avatar answered Jan 11 '23 23:01

Arup Rakshit