【问题标题】:ruby capitalize doesnt work for the first word of the titleruby capitalize 不适用于标题的第一个单词
【发布时间】:2017-07-27 00:57:20
【问题描述】:

下面的代码是将除“littleWords”和标题的第一个单词之外的所有单词大写。 (即使属于 littleWords,第一个单词也要大写。)

 def titleize (word)
    littleWords = ["and", "the", "over", "or"]

    words = Array.new
    words = word.split(" ")
    titleWords = Array.new

    words.each {|word, index| 
        if index == 0
            word = word.capitalize
        else
            unless littleWords.include?(word)
                word = word.capitalize
            end
        end
        titleWords << word
    }
    return titleWords.join(" ")
end 

测试代码如下。

it "does capitalize 'little words' at the start of a title" do
    expect(titleize("the bridge over the river chao praya")).to eq("The Bridge over         the River chao praya")
  end

但它始终将第一个“the”大写为“the”而不是“The”。我想知道我的代码的哪一部分是错误的。帮帮我……TT

【问题讨论】:

    标签: ruby capitalize


    【解决方案1】:

    您可以将String#gsub 与正则表达式和块一起使用。

    def titlesize(str, little_words)
      str.gsub(/[[:alpha:]]+/) { |w| little_words.include?(w) &
       (Regexp.last_match.begin(0) > 0) ? w : w.capitalize }
    end
    

    little_words等于数组["and", "the", "over", "of"],

    titlesize "the days of wine and roses", little_words
      #=> "The Days of Wine and Roses"
    

    Regexp::last_matchMatchData#beginRegexp.last_match 可以替换为全局变量$~

    【讨论】:

      【解决方案2】:

      这里,不使用eacheach_with_index 的另一种方式。

      def titleize (word)
          littleWords = ["and", "the", "over", "or"]
          words = word.split(" ")
          words[0].capitalize + " " + words[1..-1].map do |w|
              littleWords.include?(w) ? w : w.capitalize
          end.join(" ")
      end
      

      【讨论】:

      • 非常感谢!我也尝试将此代码应用于其他代码之一。酷:-)
      【解决方案3】:

      the documentation of Array#each 可以看出,它只为块产生一个参数:

      each { |item| block } → ary
      #      ↑↑↑↑↑↑
      

      但是,您的块有两个参数:

      words.each {|word, index| 
      #           ↑↑↑↑↑↑↑↑↑↑↑↑↑
      

      由于each 只为块产生一个参数,第二个参数将始终为nil。 (除非元素恰好是Array,否则word 将绑定到数组的第一个元素,index 绑定到第二个元素。)由于index 始终是nil,它永远不会等于0,因此永远不会进入条件的第一个分支。

      然而,还有另一种迭代方法,它实际上为块产生两个参数,元素及其索引,它被称为Enumerable#each_with_index

      words.each_with_index {|word, index| 
      #         ↑↑↑↑↑↑↑↑↑↑↑
      

      这就是您需要更改的所有内容以使您的代码正常工作。

      【讨论】:

        【解决方案4】:

        您应该使用each_with_index 而不是each 来获取index

        【讨论】:

        • 天哪!有用!太感谢了!!我投票给你。我猜 'index' 不能与 'each' 一起使用,而只能与 'each_with_index' 一起使用?
        • 是的,each 只接收 1 个参数,即值。另外,如果这解决了您的问题,请标记为正确答案
        • 对不起,我是新来的,如何标记为“正确答案”?
        猜你喜欢
        • 2016-05-26
        • 2017-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-26
        • 1970-01-01
        • 2020-02-18
        • 2017-02-26
        相关资源
        最近更新 更多