0

我觉得我真的很接近这个,但我不知道为什么.join不工作。

这是我写的代码:

class String
  def title_case
    title = self.split
    title.each do |word|
      unless (word.include?("of")) || (word.include?("the")) && (title.first != "the")
        word.capitalize!
      end
    title.join(" ")
    end
  end
end

这是 RSPEC:

describe "String" do
  describe "Title case" do
    it "capitalizes the first letter of each word" do
      "the great gatsby".title_case.should eq("The Great Gatsby")
    end
    it "works for words with mixed cases" do
      "liTTle reD Riding hOOD".title_case.should eq("Little Red Riding Hood")
    end
    it "ignores articles" do
      "The lord of the rings".title_case.should eq("The Lord of the Rings")
    end
  end
end
4

3 回答 3

2

如果你正确地格式化了代码,你会发现你打错了#join电话。它需要在each循环之外。

def title_case
  title = self.split
  title.each do |word|
    unless (word.include?("of")) || (word.include?("the")) && (title.first != "the")
      word.capitalize!
    end
  end
  title.join(" ")
end

但是使用map和非破坏性capitalize(如@xdazz 的回答)会更惯用。

于 2013-09-02T07:32:51.633 回答
2

使用.map代替.each

class String
  def title_case
    title = self.split
    title.map do |word|
      unless (word.include?("of")) || (word.include?("the")) && (title.first != "the")
        word.capitalize
      end
    end.join(" ")
  end
end
于 2013-09-02T07:33:53.017 回答
1

一点(微妙的)重新缩进显示了您的问题:

class String
  def title_case
    title = self.split
    title.each do |word|
      unless (word.include?("of")) || (word.include?("the")) && (title.first != "the")
        word.capitalize!
      end
      title.join(" ")
    end # End of each
  end # End of def
end

您将调用的值返回给each. 解决方法是在方法定义结束之后和方法定义结束之前title.join(" ")向下移动一行each

于 2013-09-02T07:36:25.947 回答