Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 892
Killerpixler Avatar asked Aug 16 '14 18:08

Killerpixler


People also ask

How do I convert a string to a symbol in Ruby?

Converting between symbols to strings is easy - use the . to_s method. Converting string to symbols is equally easy - use the . to_sym method.

How do I create a symbol in Ruby?

Ruby symbols are created by placing a colon (:) before a word. You can think of it as an immutable string. A symbol is an instance of Symbol class, and for any given name of symbol there is only one Symbol object.

What does '?' Mean in Ruby?

Functions that end with ? in Ruby are functions that only return a boolean, that is, true, or false. When you write a function that can only return true or false, you should end the function name with a question mark.

What is To_sym in Ruby?

Symbol#to_sym() : to_sym() is a Symbol class method which returns the symbol representation of the symbol object. Syntax: Symbol.to_sym() Parameter: Symbol values.


3 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

like image 131
Toby L Welch-Richards Avatar answered Oct 20 '22 19:10

Toby L Welch-Richards


You can convert a string to symbol with this:

string = "something"
symbol = :"#{string}"
like image 4
konsolebox Avatar answered Oct 20 '22 19:10

konsolebox


Or just

a = :'string'
# => :string
like image 1
emartini Avatar answered Oct 20 '22 19:10

emartini