ruby如何使用#capitalize!并保留字符串数字

Kur*_*t_S -2 ruby

所以我正在为ruby dev bootcamp做准备工作,并且需要创建一个可以大写标题的程序.我当前的代码使用#capitalize!但是当字符串中包含数字时,它被省略.

words = title.split(' ')
words.map! do |word|
  if %w(a aboard about above absent across after against along alongside amid amidst among amongst an and around as aslant astride at
    athwart atop barring before behind below beneath beside besides between beyond but by despite down during except for from in inside 
    into like mid minus near next nor notwithstanding of off on onto opposite or out outside over past per plus regarding round save 
    since so than the through throughout till times to toward towards under underneath unlike until up upon via vs. when with within 
    without worth yet ).include?(word) && word != words[0]
    word
  else
    word.capitalize!
  end
Run Code Online (Sandbox Code Playgroud)

所以什么时候what I wish I knew when I was 20输入我得到What I Wish I Knew When I Was 任何建议?

saw*_*awa 5

capitalize而不是capitalize!.

顺便说一下,如果你的意图word != words[0]是如果不是第一个单词就将单词中的任何单词保留为大写,那么你就错了.它不像那样工作.原因留给你作为家庭作业.

  • +1旁注:例如,如果`word ='A'`,也会返回`nil`,因为与数字一样,单词没有变化. (2认同)