Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Ruby classname ("NewUserBatch") to string with underscores ("new_user_batch")

Tags:

string

class

ruby

I need a generic way to convert classnames to lowercase with underscores. For example, I wish to convert the classname NewUserBatch to new_user_batch. How to do this?

like image 904
Jasper Kennis Avatar asked Oct 23 '25 03:10

Jasper Kennis


1 Answers

Underscore.

>> 'NewUserBatch'.underscore
=> "new_user_batch"

It is included in Rails so if you don't use it, you can refer to its source code.

def underscore(camel_cased_word)
  word = camel_cased_word.to_s.dup
  word.gsub!(%r::/, '/')
  word.gsub!(%r(?:([A-Za-z\d])|^)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1}#{$1 && '_'}#{$2.downcase}" }
  word.gsub!(%r([A-Z\d]+)([A-Z][a-z])/,'\1_\2')
  word.gsub!(%r([a-z\d])([A-Z])/,'\1_\2')
  word.tr!("-", "_")
  word.downcase!
  word
end
like image 122
oldergod Avatar answered Oct 24 '25 20:10

oldergod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!