这是我的代码,我不知道为什么这不会返回预期的结果: A Bunny Hops
text= "a bunny hops"
final = text.split.each{|i| i.capitalize}.join(' ')
puts final
Run Code Online (Sandbox Code Playgroud)
Aru*_*hit 11
使用以下操作Array#map:
text.split.map { |i| i.capitalize }.join(' ')
Run Code Online (Sandbox Code Playgroud)
更正和短代码:
text= "a bunny hops"
final = text.split.map(&:capitalize).join(' ')
puts final
# >> A Bunny Hops
Run Code Online (Sandbox Code Playgroud)
为什么没有你的工作:
因为Array#each方法返回已调用它的接收器本身:
text= "a bunny hops"
text.split.each(&:capitalize) # => ["a", "bunny", "hops"]
Run Code Online (Sandbox Code Playgroud)
但是Array#map返回一个新数组
text.split.map(&:capitalize) # => ["A", "Bunny", "Hops"]
Run Code Online (Sandbox Code Playgroud)
我会这样做使用String#gsub:
text= "a bunny hops"
text.gsub(/[A-Za-z']+/,&:capitalize) # => "A Bunny Hops"
Run Code Online (Sandbox Code Playgroud)
注意:我在这里使用的模式#gsub不是简单的模式.我按照帖子本身给出的字符串做了.您需要根据您将拥有的文本字符串示例进行更改.但上面是用短代码和更多Rubyish方式来做这些事情的方法.