Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on rails: replace camel case with space

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

like image 640
nish Avatar asked Feb 06 '14 11:02

nish


People also ask

Does CamelCase have spaces?

Camel case (sometimes stylized as camelCase or CamelCase, also known as camel caps or more formally as medial capitals) is the practice of writing phrases without spaces or punctuation. It indicates the separation of words with a single capitalized letter, and the first word starting with either case.

How do you convert a string to a CamelCase 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.

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

What is CamelCase in Ruby?

It's not complicated: camelCase has a lowercase first character. PascalCase has an uppercase first character. I blame rails for having a camelize method which defaults to returning PascalCase.


Video Answer


2 Answers

»  'camelCase'.underscore.humanize.upcase
=> "CAMEL CASE"
like image 182
itsnikolay Avatar answered Sep 19 '22 17:09

itsnikolay


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.

like image 32
Engr. Hasanuzzaman Sumon Avatar answered Sep 19 '22 17:09

Engr. Hasanuzzaman Sumon