Ruby 将字符串转换为符号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25342877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby turn string into symbol
提问by Killerpixler
I want to make a view helper that has a size argument ( e.g. func(size)). The issue is that this size has to be used in the function as a symbol. For example, if I pass in 'medium'into the funcI need it to be converted to :medium.
我想制作一个具有大小参数(例如func(size))的视图助手 。问题是这个大小必须在函数中用作符号。例如,如果我通过在'medium'进入func予需要它转换为:medium。
How do I do this?
我该怎么做呢?
回答by Toby L Welch-Richards
There are a number of ways to do this:
有多种方法可以做到这一点:
If your string has no spaces, you can simply to this:
如果您的字符串没有空格,您可以简单地这样做:
"medium".to_sym => :medium
"medium".to_sym => :medium
If your string has spaces, you should do this:
如果你的字符串有空格,你应该这样做:
"medium thing".gsub(/\s+/,"_").downcase.to_sym => :medium_thing
"medium thing".gsub(/\s+/,"_").downcase.to_sym => :medium_thing
Or if you are using Rails:
或者,如果您使用的是 Rails:
"medium thing".parameterize.underscore.to_sym => :medium_thing
"medium thing".parameterize.underscore.to_sym => :medium_thing
References: Convert string to symbol-able in ruby
回答by konsolebox
You can convert a string to symbol with this:
您可以使用以下方法将字符串转换为符号:
string = "something"
symbol = :"#{string}"
回答by emartini
Or just
要不就
a = :'string'
# => :string

