Skip to content

Instantly share code, notes, and snippets.

@ForeverZer0
Created September 18, 2018 22:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ForeverZer0/c3e742ec383c3d04666f82dfb0c395ec to your computer and use it in GitHub Desktop.
Save ForeverZer0/c3e742ec383c3d04666f82dfb0c395ec to your computer and use it in GitHub Desktop.
snake_case, camelCase, and PascalCase extension methods for Ruby's String class.
class String
def snake_case
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2')
.gsub(/([a-z\d])([A-Z])/,'\1_\2')
.tr("-", "_")
.downcase
end
def camel_case
sub(/^(?:(?=\b|[A-Z_])|\w)/) { $&.downcase }
.gsub(/(?:_|(\/))([a-z\d]*)/) { "#{$1}#{$2.capitalize}" }
end
def pascal_case
sub(/^[a-z\d]*/) { $&.capitalize }
.gsub(/(?:_|(\/))([a-z\d]*)/) { "#{$1}#{$2.capitalize}" }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment