Killerpixler
Killerpixler

Reputation: 4050

Ruby turn string into symbol

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 func I need it to be converted to :medium.

How do I do this?

Upvotes: 20

Views: 24934

Answers (3)

emartini
emartini

Reputation: 173

Or just

a = :'string'
# => :string

Upvotes: 1

Toby L Welch-Richards
Toby L Welch-Richards

Reputation: 817

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

Upvotes: 41

konsolebox
konsolebox

Reputation: 75458

You can convert a string to symbol with this:

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

Upvotes: 4

Related Questions