从字符串中删除双引号并转换为符号

时间:2022-09-15 13:02:12

This is very simple scenario..

这是非常简单的场景..

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

我试图从对象用户获取所有用户名和id作为哈希。

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.

我知道,有很多方法(regx或字符串函数)从字符串中删除双引号。但是,我期待非常优化和简单的解决方案。

2 个解决方案

#1


1  

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”“name @ bond”.to_sym#=>输出:“name @ bond”那么你必须要删除@'“..任何其他特殊字符

"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

这是一个参考ruby-doc符号

#2


0  

try

'test'.parameterize.underscore.to_sym

or

'test'.to_sym

#1


1  

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”“name @ bond”.to_sym#=>输出:“name @ bond”那么你必须要删除@'“..任何其他特殊字符

"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

这是一个参考ruby-doc符号

#2


0  

try

'test'.parameterize.underscore.to_sym

or

'test'.to_sym