How do I convert a sequence of words into an attribute?

116 Views Asked by At

I need to turn:

"First Name".some_method = "first_name"

I guess I could just use a regular expression, but wanted to know if there was something better. I tried constantize, and humanize, and this is pretty much the opposite of what I need to accomplish:

"first_name".humanize = "First name"
5

There are 5 best solutions below

0
Sergio Tulentsev On
require 'active_support/core_ext'

"First Name".gsub(/\s/, '').underscore # => "first_name"

I wasn't able to find the single method, though.

2
Santhosh On
"First Name".gsub(/\s+/, '_').downcase
# => "first_name" 
1
Rajarshi Das On
  irb(main):017:0> "First Name".downcase.gsub(' ', '_')
  => "first_name"
0
Arup Rakshit On

Use then String#tr as below:

"First Name".tr(" ", '_').downcase
# => "first_name"
0
Orlando On
"First Name".parameterize.underscore # => first_name