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
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
class String def to_under_score (gsub(/[A-Z]) { |p| "_" + p.downcase })[1..-1] end end
"MyTestCase".to_under_score => "my_test_case"
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
If you have access to ActiveSupport from the Rails project, it's as simple as
require 'activesupport'
"ThisIsMyString".underscore
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