7

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?

Dani Vijay
  • 2,188
  • 2
  • 22
  • 37

4 Answers4

17

humanize is your thing:

[4] pry(main)> "hello_world".humanize
"Hello world"
CAmador
  • 1,881
  • 1
  • 11
  • 19
12

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"
Cruz Nunez
  • 2,949
  • 1
  • 23
  • 33
  • This isn't working for me. When I do `> "hello_world".titleize` I get `"Hello_world"` with Rails 5.2. However `.humanize` does the trick (see below). – lucas Nov 16 '21 at 22:02
4
"hello_world".capitalize.gsub("_"," ")
=> "Hello world"
Max Williams
  • 32,435
  • 31
  • 130
  • 197
1

Rails 5 brought in a new upcase_first method: https://glaucocustodio.github.io/2016/05/19/rails-5-new-upcase-first-method/

Combine this with subbing all underscores with spaces and you should be good:

text = 'hello_world'

text.upcase_first.gsub('_', ' ')
=> 'Hello world'
Mark
  • 6,112
  • 4
  • 21
  • 46