20

I want to convert camel case words like camelCase to CAMEL CASE. I tried the approach mentioned here.

@q = params[:promo].underscore.humanize.upcase

But this gives me CAMELCASE and not CAMEL CASE same result on using:

@q = params[:promo].gsub(/[a-zA-Z](?=[A-Z])/, '\0 ').downcase

EDIT: the url contains /camelCase but on using params[:promo], the camel case is not retained and @q is camelcase

Community
  • 1
  • 1
nish
  • 6,952
  • 18
  • 74
  • 128
  • 4
    Your approach is correct and returns correct result in my console. Are you sure you your `params[:promo]` is `camelCase`, not `camelcase`? – BroiSatse Feb 06 '14 at 11:34
  • @BroiSatse: You are right, the url has `/camelCase`. But on using `params[:promo]` it becomes `camelcase`. – nish Feb 06 '14 at 11:36
  • It does work. Btw awesome Regex :) – Steve Robinson Feb 06 '14 at 11:38
  • Could you check url headers for given request? `request.original_url` – BroiSatse Feb 06 '14 at 11:51
  • @BroiSatse : it shows `camelCase` – nish Feb 06 '14 at 11:54
  • Do you have anything like `route_downcaser` installed. Also, what operating system is your server running on? – BroiSatse Feb 06 '14 at 12:00
  • @BroiSatse: i am not aware of any downcaser. But what I did was, used the required part from `request.original_url` and apllied the solution mentioned in the question. Thanks for pointing me in the right direction – nish Feb 06 '14 at 12:04

4 Answers4

34
»  'camelCase'.underscore.humanize.upcase
=> "CAMEL CASE"
itsnikolay
  • 17,415
  • 4
  • 65
  • 64
  • Uri strings must be a format with dashes and underscores (not with any kind of cammelcase) also its SEO well format – itsnikolay Feb 06 '14 at 14:36
7

If anyone need something like 'CamelCase' to 'Camel Case' can use

'CamelCase'.underscore.split('_').collect{|c| c.capitalize}.join(' ')

Or 'CamelCase' to 'camel case'

'CamelCase'.underscore.split('_').join(' ') 

Or 'CamelCase' to 'Camel case'

'CamelCase'.underscore.humanize

N.B: This solution is rails specific, it does not work in ruby without ActiveSupport.

Paul Kaplan
  • 2,885
  • 21
  • 25
Engr. Hasanuzzaman Sumon
  • 2,103
  • 3
  • 29
  • 38
4

Just replace your upper characters fist with itself prepended with a space and then make everything uppercase

'camelCase'.gsub(/[A-Z]/, ' \0').upcase
peter
  • 41,770
  • 5
  • 64
  • 108
1
'camelCase'.split(/(?=[A-Z])/).join(' ').upcase
konyak
  • 10,818
  • 4
  • 59
  • 65