简体   繁体   中英

remove double quotes from string and convert into symbol

This is very simple scenario..

I tried to get all the username and id as hash from the object user.

user = User.all
data = {}
User.map do |u|
   data[u.name.to_sym] = u.id
end

# data will be.. 
data[:"test"] = 1 ..

But, I need like this data[:test] = 1

I want to remove the double quotes from the string (begin and end) and convert into symbol.. or Is there any direct way to convert the model object into hash value what I expected?

I know, there are lot of way (regx or string functions) to remove the double quotes from the string. But, I am expecting very optimized and simple solution.

If you have name like this "name@bond"

"name@bond".to_sym #=>output :"name@bond"

then you must want to remove @ ' " .. any other special characters

"name@bond".parameterize.underscore.to_sym #=> :name_bond
"name@bond".parameterize #=> "name-bond"
"name-bond".underscore #=> "name_bond"
"name_bond".to_sym #=> :name_bond


Here's a reference ruby-doc symbols

try

'test'.parameterize.underscore.to_sym

or

'test'.to_sym

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM