Ruby使用空格首字母大写

时间:2021-11-29 09:13:19

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!

如有任何指导或帮助,我们将不胜感激。我甚至会选择正确的方向而不是答案!

3 个解决方案

#1


6  

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

这是一个你要求做的一行字:

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

string.gsub(/ ^ \ s * \ w /){ | |匹配相匹配。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.

另外,你也可以使用gsub解决你对另一个答案的评论!在不创建副本的情况下修改字符串。

#2


3  

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

this will do what you want without creating new string.

这将在不创建新字符串的情况下执行所需的操作。

#3


1  

Will this work?

这工作吗?

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

HERE

string.gsub!(/(^\s*)(\w)/) do |match|
  $1 << $2.capitalize
end

What this attempts to do is split the string on newlines, search for the first letter, capitalize it and rejoin the fragments.

这样做的目的是在换行符上分割字符串,搜索第一个字母,大写并重新加入片段。

This will produce:

这将会产生:

>           I love tacos.  I hear
   They are delicious and nutritious

#1


6  

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

这是一个你要求做的一行字:

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

string.gsub(/ ^ \ s * \ w /){ | |匹配相匹配。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.

另外,你也可以使用gsub解决你对另一个答案的评论!在不创建副本的情况下修改字符串。

#2


3  

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

this will do what you want without creating new string.

这将在不创建新字符串的情况下执行所需的操作。

#3


1  

Will this work?

这工作吗?

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

HERE

string.gsub!(/(^\s*)(\w)/) do |match|
  $1 << $2.capitalize
end

What this attempts to do is split the string on newlines, search for the first letter, capitalize it and rejoin the fragments.

这样做的目的是在换行符上分割字符串,搜索第一个字母,大写并重新加入片段。

This will produce:

这将会产生:

>           I love tacos.  I hear
   They are delicious and nutritious