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?
Converting between symbols to strings is easy - use the . to_s method. Converting string to symbols is equally easy - use the . to_sym method.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With