驼峰 转 蛇形
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
 end
end
那么你可以做有趣的东西:
"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! }
 end
end
所以"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‘).
 downcase
end
"FooBar".snake_case   #=> "foo_bar"
"HeadlineCNNNews".snake_case #=> "headline_cnn_news"
"CNN".snake_case    #=> "cnn"
原文:http://www.cnblogs.com/qinyan20/p/4211635.html