From: tamouse mailing lists Date: 2013-02-19T12:23:39+09:00 Subject: Re: Adding camelize and underscore to String On Mon, Feb 18, 2013 at 12:07 AM, Rob Marshall wrote: > I know this is just a silly question, and that these methods are > available in Rails, but is this a viable way to add them to Ruby withOUT > Rails? e.g.: Not silly. Sometimes it *is* easier to reinvent the wheel, if the wheel is easy to reinvent. > class String > def camelize > self.split("_").each {|s| s.capitalize! }.join("") > end > def camelize! > self.replace(self.split("_").each {|s| s.capitalize! }.join("")) > end > def underscore > self.scan(/[A-Z][a-z]*/).join("_").downcase > end > def underscore! > self.replace(self.scan(/[A-Z][a-z]*/).join("_").downcase) > end > end I do this a bit differently: class String def camelize self = self.dup self.camelize! end def camelize! self.replace... # as you have it end def underscore self = self.dup self.underscore! end def underscore! self.replace... # as you have it end end I've also seen it done instead of monkey patching, to insert a new module into String: module Camelizer # method defs as above end String.send(:include Camelizer)