Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting snake case to normal sentence in Ruby

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?

like image 360
Dani Vijay Avatar asked May 21 '19 13:05

Dani Vijay


People also ask

What is snake case in Ruby?

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".

How do you convert a string to a camel case in Ruby?

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.

How do I convert to Ruby?

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.

How do you capitalize the first letter in Ruby?

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.


3 Answers

humanize is your thing:

[4] pry(main)> "hello_world".humanize
"Hello world"
like image 91
CAmador Avatar answered Oct 12 '22 23:10

CAmador


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"
like image 39
Cruz Nunez Avatar answered Oct 13 '22 01:10

Cruz Nunez


"hello_world".capitalize.gsub("_"," ")
=> "Hello world"
like image 4
Max Williams Avatar answered Oct 12 '22 23:10

Max Williams