From: Robert Dober Date: 2007-08-23T05:02:27+09:00 Subject: Re: de-camelcase a filename On 8/22/07, David A. Black wrote: > 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 > Sure that is quite clever, but it will e.g. fail on "AMACAddress" which I want to have as a_mac_address, well but that was a little side issue of Dan, I guess this is the best solution for OP's problem. I just wanted to point Dan to the fact that he would need a dictionary. Cheers Robert -- I'm an atheist and that's it. I believe there's nothing we can know except that we should be kind to each other and do what we can for other people. -- Katharine Hepburn