首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将字符串转换为标题大小写

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

Stack Overflow用户
提问于 2015-07-09 04:00:36
回答 3查看 973关注 0票数 2

所以我是Ruby的新手,我的任务是手动将字符串转换为title-case。我终于能够创建一种我相信能够满足我的任务要求的方法(它不是很灵活,但它可以做到),但是我遇到了最后一个障碍。我似乎不能将最后一个数组连接到一个字符串中。我的代码和Rspec错误如下。我认为我必须在某个地方使用.join(“"),但我不确定确切的语法。提前感谢您的帮助!

我的代码:

代码语言:javascript
复制
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:

代码语言:javascript
复制
expected: "The Great Gatsby"
     got: ["The", "Great", "Gatsby"]

(compared using ==)

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

再一次:

代码语言:javascript
复制
expected: "Little Red Riding Hood"
     got: ["Little", "Red", "Riding", "Hood"]

(compared using ==)

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

再一次:

代码语言:javascript
复制
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)>'

再一次:

代码语言:javascript
复制
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)>'
EN

回答 3

Stack Overflow用户

发布于 2015-07-09 04:05:02

快速解决方案:

代码语言:javascript
复制
  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

如果你想用红宝石的方式去做:

代码语言:javascript
复制
def fix
  string.split(" ").map(&:capitalize).join(" ")
end
票数 3
EN

Stack Overflow用户

发布于 2015-07-09 04:44:12

ActiveSupport提供了一个名为titleize的方法,它可以完成您所描述的操作:

代码语言:javascript
复制
>> "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

票数 1
EN

Stack Overflow用户

发布于 2015-07-09 04:55:49

要提供替代解决方案,请执行以下操作:

代码语言:javascript
复制
def fix
  string.downcase.gsub(/^\S+|(\S{4,})/, &:capitalize)
end

这只是将出现在字符串开头或长度为4+个字符的每个单词替换为其大写形式。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31302550

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档