Reputation: 12122
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.
Upvotes: 0
Views: 2739
Reputation: 134
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
Upvotes: 2
Reputation: 1861
try
'test'.parameterize.underscore.to_sym
or
'test'.to_sym
Upvotes: 0