Last active
August 21, 2018 19:39
-
-
Save mohammedri/f87a6f6ebdef46219993bcd378125c1e to your computer and use it in GitHub Desktop.
[Ruby] Convert from snake_case to camel_case
This file contains 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
# 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