Ruby turn string into symbol

Hi 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 :size i.e. if I pass in medium into the func I need it to be converted to :medium.

How do I do this?

Answers


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


You can convert a string to symbol with this:

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

Or just

a = :'string'
# => :string

Need Your Help

Sails.js find multiple database entries by id

javascript node.js mongodb sails.js waterline

I'm bit new at node.js/sails.js and was wondering (if possible) how to retrieve multiple database entries by searching for their ids - there is something like this mentioned in the MongoDB document...

What is the difference between procedural programming and functional programming?

functional-programming glossary paradigms procedural-programming

I've read the Wikipedia articles for both procedural programming and functional programming, but I'm still slightly confused. Could someone boil it down to the core?