Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created October 28, 2016 08:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/b3f22d5bcb8555deea1707b84d294045 to your computer and use it in GitHub Desktop.
Save komasaru/b3f22d5bcb8555deea1707b84d294045 to your computer and use it in GitHub Desktop.
Ruby script to convert CamelCase and snake_case each other.
class String
def to_camel
self.split(/_/).map(&:capitalize).join
# or
#self.split(/_/).map{ |w| w[0] = w[0].upcase; w }.join
end
def to_snake
self.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
.gsub(/([a-z\d])([A-Z])/, '\1_\2')
.downcase
end
end
src = "CamlCase1ASnakeCase2B"
puts " SRC: #{src}"
snake = "CamlCase1ASnakeCase2B".to_snake
puts "SNAKE: #{snake}"
camel = snake.to_camel
puts "CAMEL: #{camel}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment