将字符串转换为标题大小写

时间:2013-09-02 07:29:07

标签: ruby rspec

我觉得我真的很接近这个,但我无法弄清楚为什么.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

3 个答案:

答案 0 :(得分: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的答案)会更加惯用。

答案 1 :(得分: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

答案 2 :(得分: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向下移动一行。