Created
November 29, 2020 03:56
-
-
Save ForeverZer0/e74363ba8ab0a0026ad4f26404d92993 to your computer and use it in GitHub Desktop.
Convert from camelCase/PascalCase to snake_case in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def snake_case | |
| return downcase if match(/\A[A-Z]+\z/) | |
| gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2'). | |
| gsub(/([a-z])([A-Z])/, '\1_\2'). | |
| downcase | |
| end | |
| "FooBar".snake_case #=> "foo_bar" | |
| "HeadlineCNNNews".snake_case #=> "headline_cnn_fake_news" | |
| "CNN".snake_case #=> "cnn" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment