Ruby turn string into symbol

ID : 274550

viewed : 35

Tags : ruby-on-railsrubyruby-on-railsruby





Top 4 Answer for Ruby turn string into symbol

vote vote

99

There are a number of ways to do this:

If your string has no spaces, you can simply to this:

"medium".to_sym => :medium

If your string has spaces, you should do this:

"medium thing".gsub(/\s+/,"_").downcase.to_sym => :medium_thing

Or if you are using Rails:

"medium thing".parameterize.underscore.to_sym => :medium_thing

References: Convert string to symbol-able in ruby

vote vote

89

You can convert a string to symbol with this:

string = "something" symbol = :"#{string}" 
vote vote

77

Or just

a = :'string' # => :string 
vote vote

60

Top 3 video Explaining Ruby turn string into symbol







Related QUESTION?