重新利用第一个词

时间:2015-05-16 00:54:46

标签: ruby

所以很明显这个问题之前已被问过,但我实际上问的是我所编写的代码的具体内容。基本上我把这些词大写(标题化)。我的方法没有经过优化,而且确实是圆形的,所以请耐心等待。一旦我再次降低标题,我似乎无法对标题的第一个字进行资本重组。我在代码中写了一些注释,因此您可以轻松浏览它而无需分析整个内容。我没有要求你写一个新代码因为我可以谷歌那个。我更感兴趣的是为什么我的解决方案不起作用..

input: "the hamster and the mouse"
output: "the Hamster and the Mouse"
WHAT I WANT: "The Hamster and the Mouse"


class String
  def titleize
    #regex reads: either beginning of string or whitespace followed by alpha
    self.gsub(/(\A|\s)[a-z]/) do |letter|
      letter.upcase!
    end
  end
end

class Book
  attr_accessor :title

  def title=(title)
    @title = title.titleize #makes every word capitalized

    small_words = %w[In The And A An Of]
    words = @title.split(" ")

    #makes all the "small_words" uncapitalized again

    words.each do |word|
      if small_words.include?(word)
        word.downcase!
      end
    end

    words[0][0].upcase! #doesnt work
    @title = words.join(" ")

    #NEED TO MAKE FIRST WORD CAPITALIZED EVEN IF ITS A "small_word"
    @title[0].upcase! #also doesnt work

  end

2 个答案:

答案 0 :(得分:1)

[(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 6, 7), (1, 6, 8), (1, 6, 9), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 6, 7), (2, 6, 8), (2, 6, 9), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 6, 7), (3, 6, 8), (3, 6, 9)] 替换为words[0][0].upcase!。这将标题化标题中的第一个单词,这就是你想要的。

您也不需要words[0] = words[0].titleize

答案 1 :(得分:0)

更改最后一行:

@title[0].upcase!

要:

@title.capitalize!

修改 我重写了课程。线路较少,您不需要RegEx或String#titleize方法。

class Book
    attr_reader :title

    def title=(title)
        small_words = ["in", "the", "and", "a", "an", "of"]

        @title = title.split.each do |word|
            small_words.include?(word.downcase) ? word.downcase! : word.capitalize!
        end

        @title[0].capitalize!
        @title = @title.join(" ")
    end
end

new_book = Book.new
new_book.title="the hamster and the mouse"
new_book.title # => "The Hamster and the Mouse"