Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby capitalize first character with spaces

Tags:

ruby

Some rules: must use capitalization (not upcase or any other expression)

Stuck on the following:

string = <<-HERE
              i love tacos.  I hear
   they are delicious and nutritious

HERE

I need to capitalize the first word of each line with the whitespace and am having trouble figuring out how to get it done:

The output needs to look as follows:

              I love tacos.  I hear
   They are delicious and nutritious

Any guidance or help will be greatly appreciated. I'll even take a point in the right direction rather than an answer!

like image 201
jtm Avatar asked Feb 23 '26 01:02

jtm


1 Answers

Here's a one-liner that does what you asked for:

string.gsub(/^\s*\w/) {|match| match.upcase }

I know you said "no upcase", but in this context, it's only upcasing the first letter. Let me know if you have any questions about it.

And to address your comment on the other answer, you can always use gsub! to mutate the string in place without creating a copy.

like image 96
Cade Avatar answered Feb 25 '26 14:02

Cade