Skip to content

Instantly share code, notes, and snippets.

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 avdgaag/48937 to your computer and use it in GitHub Desktop.
Save avdgaag/48937 to your computer and use it in GitHub Desktop.
Example regular expressions for converting strings to CamelCase or snake_case
original = 'ThisIsAStringInCamelCaseWithNumbersLike12And14'
# Convert a CamelCase string to snake_case
snake_case = original.gsub(/([\w^_](?=[A-Z]))|([a-z](?=\d+))/, '\1\2_').downcase
# Convert a snake_case string to CamelCase
camel_case = snake_case.gsub(/^\w|_\w/) { |match| match[-1,1].upcase }
puts snake_case # => "this_is_a_string_in_camel_case_with_numbers_like_12_and_14"
puts camel_case # => "ThisIsAStringInCamelCaseWithNumbersLike12And14"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment