首页 > 代码库 > 字符串 驼峰 蛇形

字符串 驼峰 蛇形

驼峰 转 蛇形

CamelCase.camelize

 

 蛇形驼峰

1. Rails的的ActiveSupport 加上下划线为以下几点:

class String def underscore self.gsub(/::/, ‘/‘). gsub(/([A-Z]+)([A-Z][a-z])/,‘\1_\2‘). gsub(/([a-z\d])([A-Z])/,‘\1_\2‘). tr("-", "_"). downcase endend

那么你可以做有趣的东西:

"CamelCase".underscore



2. 一个班轮ruby

class String # ruby mutation methods have the expectation to return self if a mutation occurred, nil otherwise. (see  CodeGo.net  def to_underscore!  gsub!(/(.)([A-Z])/,‘\1_\2‘)  downcase! end def to_underscore  dup.tap { |s| s.to_underscore! } endend

所以"SomeCamelCase".to_underscore # =>"some_camel_case"

3. 下面是Rails如何做的:

 def underscore(camel_cased_word)  camel_cased_word.to_s.gsub(/::/, ‘/‘).  gsub(/([A-Z]+)([A-Z][a-z])/,‘\1_\2‘).  gsub(/([a-z\d])([A-Z])/,‘\1_\2‘).  tr("-", "_").  downcase end



4. 接收器转换成蛇的情况下: 这是DataMapper的和Merb的支持库。 (

def snake_case return downcase if match(/\A[A-Z]+\z/) gsub(/([A-Z]+)([A-Z][a-z])/, ‘\1_\2‘). gsub(/([a-z])([A-Z])/, ‘\1_\2‘). downcaseend"FooBar".snake_case   #=> "foo_bar""HeadlineCNNNews".snake_case #=> "headline_cnn_news""CNN".snake_case    #=> "cnn"

字符串 驼峰 蛇形