I'm trying to convert a string in snake case to normal case(Eg: "hello_world" to "Hello world")
I'm pretty new to ruby, and I'm using it with Rails. I found this question Converting string from snake_case to CamelCase in Ruby, and it seems like there is a function for that usecase (.camelize
). Is there anything that I can use inbuilt like that? If not, how can I achieve this?
permalink #snakecase ⇒ Object Also known as: underscoreUnderscore a string such that camelcase, dashes and spaces are replaced by underscores. This is the reverse of #camelcase, albeit not an exact inverse. "SnakeCase".
permalink #camelcase(*separators) ⇒ ObjectConverts a string to camelcase. This method leaves the first character as given. This allows other methods to be used first, such as #uppercase and #lowercase. Custom separators can be used to specify the patterns used to determine where capitalization should occur.
Ruby provides the to_i and to_f methods to convert strings to numbers. to_i converts a string to an integer, and to_f converts a string to a float. When you run the program, you'll get what may feel like an unexpected answer: ruby adder.
Ruby | String capitalize() Method capitalize is a String class method in Ruby which is used to return a copy of the given string by converting its first character uppercase and the remaining to lowercase.
humanize is your thing:
[4] pry(main)> "hello_world".humanize
"Hello world"
Rails has a method called titleize
"hello_world".titleize # => "Hello World"
Ruby has a method called capitalize
"hello_world".capitalize # => "Hello_world"
If you want "Hello world" with only the "H" capitalized, combine them both (in Rails).
"hello_world".titleize.capitalize # => "Hello world"
"hello_world".capitalize.gsub("_"," ")
=> "Hello world"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With