I am trying to convert a name from snake case to camel case. Are there any built-in methods?
Eg: \"app_user\" to \"AppUser\"
(I hav
I feel a little uneasy to add more answers here. Decided to go for the most readable and minimal pure ruby approach, disregarding the nice benchmark from @ulysse-bn. While :class mode is a copy of @user3869936, the :method mode I don't see in any other answer here.
def snake_to_camel_case(str, mode: :class)
case mode
when :class
str.split('_').map(&:capitalize).join
when :method
str.split('_').inject { |m, p| m + p.capitalize }
else
raise "unknown mode #{mode.inspect}"
end
end
Result is:
[28] pry(main)> snake_to_camel_case("asd_dsa_fds", mode: :class)
=> "AsdDsaFds"
[29] pry(main)> snake_to_camel_case("asd_dsa_fds", mode: :method)
=> "asdDsaFds"