From: "David A. Black" Date: 2007-08-23T04:05:43+09:00 Subject: Re: de-camelcase a filename Hi -- On Thu, 23 Aug 2007, Robert Dober wrote: > On 8/22/07, Daniel Berger wrote: >> On Jul 2, 11:42 am, Ezra Zygmuntowicz wrote: >>> On Jul 2, 2007, at 9:41 AM, Bill Kelly wrote: >>> >>>> From: "Roseanne Zhang" >>>>> How about this: >>>>> "FooBarBaz".split(/(?=[A-Z])/).join('_').downcase >>> >>>> Nice... (why didn't I think of that :) >>> >>> This is the cleanest I've come up with: >>> >>> class String >>> # "FooBar".snake_case #=> "foo_bar" >>> def snake_case >>> gsub(/\B[A-Z]/, '_\&').downcase >>> end >>> end >> >> Both of these solutions have a problem with back to back caps. For >> example: >> >> "CheckHostIP".gsub(/\B[A-Z]/, '_\&').downcase => "check_host_i_p" >> >> But I want "check_host_ip". It's probably a simple tweak, but I'm >> having trouble finding it at the moment. Suggestions? >> >> Thanks, >> >> Dan > > I guess there can be no general solution, I would like > HostIP --> host_ip > but > AHostIP --> a_host_ip Here's how ActiveSupport does it: 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 David -- * Books: RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242) RUBY FOR RAILS (http://www.manning.com/black) * Ruby/Rails training & consulting: Ruby Power and Light, LLC (http://www.rubypal.com)