Ruby on Rails: Converting “SomeWordHere” to “some word here”

前端 未结 4 1064
夕颜
夕颜 2021-01-08 00:29

I know you can do something like:

\"SomeWordHere\".underscore.gsub(\"_\", \" \") 

to get \"some word here\".

I thought that might

相关标签:
4条回答
  • 2021-01-08 00:30

    alt text

    The methods underscore and humanize are designed for conversions between tables, class/package names, etc. You are better off using your own code to do the replacement to avoid surprises. See comments.

    "SomeWordHere".underscore => "some_word_here"
    
    "SomeWordHere".underscore.humanize => "Some word here"
    
    "SomeWordHere".underscore.humanize.downcase => "some word here"
    
    0 讨论(0)
  • 2021-01-08 00:43

    Nope there is no built-in method that I know of. Any more efficient then a one-liner? Don't thinks so. Maybe humanize instead of the gsub, but you don't get exactly the same output.

    0 讨论(0)
  • 2021-01-08 00:44

    I think this is a simpler solution:

    "SomeWordHere".titleize.downcase

    0 讨论(0)
  • 2021-01-08 00:53

    You can use a regular expression:

    puts "SomeWordHere".gsub(/[a-zA-Z](?=[A-Z])/, '\0 ').downcase
    

    Output:

    some word here
    

    One reason you might prefer this is if your input could contain dashes or underscores and you don't want to replace those with spaces:

    puts "Foo-BarBaz".underscore.gsub('_', ' ')
    puts "Foo-BarBaz".gsub(/[a-zA-Z](?=[A-Z])/, '\0 ').downcase
    

    Output:

    foo bar baz
    foo-bar baz
    
    0 讨论(0)
提交回复
热议问题