Benjamin Kudria
7/2/2007 2:42:00 PM
On Saturday, June 30 2007, Bill Kelly wrote:
> From: "Swaroop C H" <swaroopch@gmail.com>
>
> > On 6/30/07, Aaron Smith <beingthexemplary@gmail.com> wrote:
> >> how can a take a string file name like MyTestCase.rb and change it to
> >> my_test_case.rb?
> >
> > I'm a novice at Ruby, but this might help:
> >
> > irb(main):013:0> 'MyTestCase'.gsub(/[A-Z]/) {
> > irb(main):014:1* |p| '_' + p.downcase
> > irb(main):015:1> }
> > => "_my_test_case"
> >
> > then:
> >
> > irb(main):020:0> "_my_test_case"[1..-1]
> > => "my_test_case"
>
> Here's another way:
>
> irb(main):078:0> "FooBarBaz".split(/(?=[A-Z])/).map{|w|
> w.downcase}.join("_") => "foo_bar_baz"
After seeing this split -> map -> join in my scripts, I came up with smj:
class String
def smj(s, j=s, &b)
r = self.split(s).map(&b)
j ? r.join(j) : r
end
end
So the above would become:
"FooBarBaz".smj(/(?=[A-Z])/, '_') { |w| w.downcase } #=> "foo_bar_baz"
I love Pe...Ruby! I love Ruby!
-Ben Kudria