views:

155

answers:

4

Hi,

I'm sure this is an easy one for you geeks:

Say I have a String "ThisIsMyString" and I want to format it like "this_is_my_string" using Ruby.

How do I do that?

Matt

+2  A: 

class String def to_under_score (gsub(/[A-Z]) { |p| "_" + p.downcase })[1..-1] end end

"MyTestCase".to_under_score => "my_test_case"

From http://www.ruby-forum.com/topic/113697#265696

mcandre
+1  A: 

Ruby Facets has a function to do this: String#underscore. Here's the source of it:

  def underscore
    gsub(/::/, '/').
    gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
    gsub(/([a-z\d])([A-Z])/,'\1_\2').
    tr("-", "_").
    downcase
  end
Pesto
+1  A: 

If you have access to ActiveSupport from the Rails project, it's as simple as

require 'activesupport'
"ThisIsMyString".underscore
Lars Haugseth
Just curious why my answer (who preceded the accepted answer by a minute or two and is essentially the same) got downvoted.
Lars Haugseth
yeah, that seems a bit harsh. Maybe because you did the unnecessary (if you assume that it's a Rails project) require?
Pete Hodgson
+5  A: 

If you have access to ActiveSupport (as in Rails, but usable externally) you can use the underscore method in the Inflector module.

"ClassName".underscore # => class_name
Sarah Mei
that's the method I was missing! thanks!
Matt