Skip to content

Instantly share code, notes, and snippets.

Revisions

  1. avdgaag renamed this gist Jan 19, 2009. 1 changed file with 0 additions and 0 deletions.
  2. avdgaag created this gist Jan 19, 2009.
    10 changes: 10 additions & 0 deletions Ruby regular expression for CamelCase and snake_case
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    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"