Is there any ready function which converts camel case Strings into underscore separated string? I want something like this
"CamelCaseString".to_undescore
to return "camel_case_string"
Is there any ready function which converts camel case Strings into underscore separated string? I want something like this
"CamelCaseString".to_undescore
to return "camel_case_string"
Rails' ActiveSupport adds underscore to the String using the following:
class String
def underscore(camel_cased_word)
camel_cased_word.to_s.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
end
Then you can do fun stuff:
"CamelCase".underscore
Here's how Rails does it:
def underscore(camel_cased_word)
camel_cased_word.to_s.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
One-liner Ruby implementation:
class String
def to_underscore!
self.gsub!(/(.)([A-Z])/,'\1_\2').downcase!
end
def to_underscore
self = self.clone.to_underscore!
end
end
So "SomeCamelCase".to_underscore # =>"some_camel_case"