Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - convert from symbol to variable

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.

like image 297
BuddyJoe Avatar asked Oct 06 '09 17:10

BuddyJoe


People also ask

How do I convert a symbol to a string 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.

What is @variable in Ruby?

@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.

How do symbols work in Ruby?

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.

What is Colon 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. :apple.object_id.


2 Answers

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
like image 150
sepp2k Avatar answered Nov 06 '22 18:11

sepp2k


You could use eval

def foo(bar)
  eval(bar.to_s).some_method_call
end
like image 26
madlep Avatar answered Nov 06 '22 17:11

madlep