Ruby on Rails uncapitalize first letter

前端 未结 10 1491
感动是毒
感动是毒 2021-02-03 19:48

I\'m running Rails 2.3.2.

How do I convert \"Cool\" to \"cool\"? I know \"Cool\".downcase works, but is there a Ruby/Rails method

相关标签:
10条回答
  • 2021-02-03 20:04

    You can use tap (so that it fits on one line):

    "JonSkeet".tap { |e| e[0] = e[0].downcase } # => "jonSkeet"
    
    0 讨论(0)
  • 2021-02-03 20:09
    str = "Directly to the south"
    str[0] = str[0].downcase
    puts str
    #=> "directly to the south"
    
    0 讨论(0)
  • 2021-02-03 20:10
    name = "Viru"
    
    name = name.slice(0).downcase + name[1..(name.length)]
    
    0 讨论(0)
  • 2021-02-03 20:13

    Try this

    'Cool'.sub(/^([A-Z])/) { $1.tr!('[A-Z]', '[a-z]') }
    

    https://apidock.com/ruby/XSD/CodeGen/GenSupport/uncapitalize

    0 讨论(0)
  • 2021-02-03 20:16

    You could also do this with a simple sub:

    "Cool".sub(/^[A-Z]/) {|f| f.downcase }
    
    0 讨论(0)
  • 2021-02-03 20:17

    There is no inverse of capitalize, but you can feel free to roll your own:

    class String
      def uncapitalize 
        self[0, 1].downcase + self[1..-1]
      end
    end
    
    0 讨论(0)
提交回复
热议问题