From: Matthew Kerwin Date: 2013-02-19T08:11:33+09:00 Subject: Re: Adding camelize and underscore to String Rob Marshall wrote in post #1097665: > Another couple questions, sorry... > > In Python regular expressions have a "findall" which was added in > version 1.5.2 (i.e. it's been around for quite some time, relatively > :-). Is the use of gsub in Ruby because scan is a recent addition to > String? Or is it just, for heavy use, too slow? Scan is used to extract matches. The following: .split("_").each {|s| s.capitalize! }.join("") .scan(/[A-Z][a-z]*/).join("_").downcase ..both construct a new array object containing a bunch of new string objects, and iterate over the array, etc. sub and gsub work directly on the original string without necessarily constructing all those intermediate variables, instead using the internal state of the regular expression engine. So in theory: my_c_string.gsub(/_([a-z])/) { $1.upcase } my_j_string.gsub(/[A-Z]/) { "_#{$&.downcase}" } or their more advanced cousins in ActiveSupport work faster and cleaner, in a single fell swoop. I believe it's a matter of taste as to which is more readable, but personally I think the gsub versions get to the point more readily. > Also, is my use of self.replace() OK? I know that any methods with a '!' > are supposed to tell the user: Beware. But I wasn't sure if modifying > self is a "normal" way to implement the '!' methods. That's how I always do it. If you're wrong, we both are. ;) -- Posted via http://www.ruby-forum.com/.