How can I convert :obj back into a variable called obj inside the def?
def foo(bar)
bar.some_method_call
end
foo :obj
UPDATE: The final code is more elaborate than this but...
I like to be able to say
foo :obj
instead of
foo obj
I working on some DSL-like syntax. And this one change would let things read a little clearer.
Converting between symbols to strings is easy - use the . to_s method. Converting string to symbols is equally easy - use the . to_sym method.
@variable s are called instance variables in ruby. Which means you can access these variables in ANY METHOD inside the class. [ Across all methods in the class] Variables without the @ symbol are called local variables, which means you can access these local variables within THAT DECLARED METHOD only.
Ruby symbols are defined as “scalar value objects used as identifiers, mapping immutable strings to fixed internal values.” Essentially what this means is that symbols are immutable strings. In programming, an immutable object is something that cannot be changed.
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. :apple.object_id.
What kind of variable is obj
in your example? If it's a local variable of the scope where foo is called, it can't be accessed from inside foo, unless you pass the current binding as a second parameter.
If you want to access the instance variable @obj
, it's easy:
def foo(bar)
instance_variable_get("@#{bar}").length
end
@obj = "lala"
foo("obj") #=> 4
You could use eval
def foo(bar)
eval(bar.to_s).some_method_call
end
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