Ruby on Rails uncapitalize first letter

不想你离开。 提交于 2019-12-03 10:32:54

问题


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 that does the opposite of capitalize, i.e., uncapitalize or decapitalize?


回答1:


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



回答2:


There is also:

"coolat_cat".camelize(:lower) # => "coolCat"



回答3:


You could also do this with a simple sub:

"Cool".sub(/^[A-Z]/) {|f| f.downcase }



回答4:


str = "Directly to the south"
str[0] = str[0].downcase
puts str
#=> "directly to the south"



回答5:


There is no real inverse of capitalize, but I think underscore comes close.

"CoolCat".underscore  #=> "cool_cat"
"cool_cat".capitalize #=> "Cool_cat"
"cool_cat".camelize   #=> "CoolCat"

Edit: underscore is of course the inverse of camelize, not capitalize.




回答6:


There is an inverse of capitalize called swapcase:

"Cool Cat".swapcase   #=> "cOOL cAT"



回答7:


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

"JonSkeet".tap { |e| e[0] = e[0].downcase } # => "jonSkeet"



回答8:


If you use Ruby Facets, you can lowercase the first letter:

https://github.com/rubyworks/facets/blob/master/lib/core/facets/string/uppercase.rb




回答9:


Try this

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

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




回答10:


name = "Viru"

name = name.slice(0).downcase + name[1..(name.length)]


来源:https://stackoverflow.com/questions/4474028/ruby-on-rails-uncapitalize-first-letter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!