Converting upper-case string into title-case using Ruby

后端 未结 10 1372
小鲜肉
小鲜肉 2020-12-25 10:46

I\'m trying to convert an all-uppercase string in Ruby into a lower case one, but with each word\'s first character being upper case. Example:

convert \"MY STRING HE

相关标签:
10条回答
  • 2020-12-25 11:38
    "MY STRING HERE".titlecase
    

    Does the job (it's a method in the Rails gem, however) http://apidock.com/rails/String/titlecase

    0 讨论(0)
  • 2020-12-25 11:38

    Unicode-aware titlecase for Ruby 2.4.0+:

    class String
      def titlecase
        split(/([[:alpha:]]+)/).map(&:capitalize).join
      end
    end
    
    >> "я только что посмотрел \"леди исчезает\", и это чума!".titlecase
    => "Я Только Что Посмотрел \"Леди Исчезает\", И Это Чума!"
    

    (based on https://stackoverflow.com/a/1792102/788700)

    0 讨论(0)
  • 2020-12-25 11:41
    string = "MY STRING HERE"
    string.split(" ").map {|word| word.capitalize}.join(" ")
    

    The way this works: The .split(" ") splits it on spaces, so now we have an array that looks like ["my", "string", "here"]. The map call iterates over each element of the array, assigning it to temporary variable word, which we then call capitalize on. Now we have an array that looks like ["My", "String", "Here"], and finally we turn that array back into a string by joining each element with a space (" ").

    0 讨论(0)
  • 2020-12-25 11:47

    Capitalizes every word in a sentence using ruby, without regex.. because unfortunately those scare me

    class Book
        attr_accessor :title
        def title=(new_title)
            result = []
            words = new_title.split(' ')
            words.each do |word|
                capitalized = word[0].upcase + word[1..word.length].downcase
                result.push(capitalized)
            end
    
            @title = result.join(' ')
        end
    end
    
    0 讨论(0)
提交回复
热议问题