Converting camel case to underscore case in ruby
Is there any ready function which converts camel case Strings into underscore separated string?
I want something like this:
"CamelCaseString".to_underscore
to return "camel_case_string".
...
Solution 1:
Rails' ActiveSupport adds underscore to the String using the following:
class String
def underscore
self.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
=> "camel_case"
Solution 2:
You can use
"CamelCasedName".tableize.singularize
Or just
"CamelCasedName".underscore
Both options ways will yield "camel_cased_name"
. You can check more details it here.
Solution 3:
One-liner Ruby implementation:
class String
# ruby mutation methods have the expectation to return self if a mutation occurred, nil otherwise. (see http://www.ruby-doc.org/core-1.9.3/String.html#method-i-gsub-21)
def to_underscore!
gsub!(/(.)([A-Z])/,'\1_\2')
downcase!
end
def to_underscore
dup.tap { |s| s.to_underscore! }
end
end
So "SomeCamelCase".to_underscore # =>"some_camel_case"
Solution 4:
There is a Rails inbuilt method called 'underscore' that you can use for this purpose
"CamelCaseString".underscore #=> "camel_case_string"
The 'underscore' method can typically be considered as inverse of 'camelize'
Solution 5:
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