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

时间:2015-07-08 20:00:36

标签: ruby-on-rails ruby rspec

所以我在Ruby中有点像菜鸟,我的任务是手动将字符串转换为标题大小写。我终于能够创建一种方法,我相信它将满足我的作业要求(它不是很灵活,但它会做到),但是我遇到了最后一个问题。我似乎无法将最终数组加入一个字符串。我的代码和Rspec错误如下。我相信我必须在某处使用.join(""),但我不确定确切的语法。在此先感谢您的帮助!

我的代码:

class Title
  attr_accessor :string

  def initialize(string)
    @string = string
  end

  def fix
    string.split(" ").each_with_index do |value, index|
      if index >= 2 && value.length <= 3
        value.downcase!
      else
        value.capitalize!
      end
    end
  end
end

Rspec的:

expected: "The Great Gatsby"
     got: ["The", "Great", "Gatsby"]

(compared using ==)

exercise_spec.rb:6:in `block (3 levels) in <top (required)>'

再次:

expected: "Little Red Riding Hood"
     got: ["Little", "Red", "Riding", "Hood"]

(compared using ==)

exercise_spec.rb:9:in `block (3 levels) in <top (required)>'

再次:

expected: "The Lord of the Rings"
     got: ["The", "Lord", "of", "the", "Rings"]

(compared using ==)

exercise_spec.rb:12:in `block (3 levels) in <top (required)>'

再次:

expected: "The Sword and the Stone"
     got: ["The", "Sword", "and", "the", "Stone"]

(compared using ==)

exercise_spec.rb:17:in `block (3 levels) in <top (required)>'

3 个答案:

答案 0 :(得分:3)

快速修复:

  def fix
    string.split(" ").each_with_index do |value, index|
      if index >= 2 && value.length <= 3
        value.downcase!
      else
        value.capitalize!
      end
      value
    end.join(" ")
  end

如果你想要红宝石的方式:

def fix
  string.split(" ").map(&:capitalize).join(" ")
end

答案 1 :(得分:1)

ActiveSupport提供了一个名为titleize的方法,可以执行您所描述的内容:

>> "the great gatsby".titleize
=> "The Great Gatsby"
>> "little red riding hood".titleize
=> "Little Red Riding Hood"
>> "the lord of the rings".titleize
=> "The Lord Of The Rings"

来源:http://apidock.com/rails/ActiveSupport/Inflector/titleize

答案 2 :(得分:0)

提供替代解决方案:

def fix
  string.downcase.gsub(/^\S+|(\S{4,})/, &:capitalize)
end

这只是替换出现在字符串开头的每个单词,或者是大写字母长度超过4个字符。