Skip to content

Instantly share code, notes, and snippets.

@mohammedri
Last active August 21, 2018 19:39
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 mohammedri/f87a6f6ebdef46219993bcd378125c1e to your computer and use it in GitHub Desktop.
Save mohammedri/f87a6f6ebdef46219993bcd378125c1e to your computer and use it in GitHub Desktop.
[Ruby] Convert from snake_case to camel_case
# Using gsub (least performant)
"test_string".capitalize.gsub(/_(\w)/){$1.upcase} # => TestString
# Using split & map with capitalize
"test_string".split('_').map(&:capitalize).join
# Using split & map (most performant)
"test_string".split('_').map{|e| e.capitalize}.join
# Ruby string implementation
http://rubydoc.info/gems/extlib/0.9.15/String#camel_case-instance_method
def camel_case
return self if self !~ /_/ && self =~ /[A-Z]+.*/
split('_').map{|e| e.capitalize}.join
end
# Extra
"hello_world".split('_').collect(&:capitalize).join #=> "HelloWorld"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment