2

it's possible in rails convert variable name to string?

Example: stack_overflow = "Fantastic!".

by stack_overflow.to_sym I'll get :Fantastic!. Instead I would => :stack_overflow

and, if it were possibile, this would be bad programming cause unsafe code?

Thanks :-)

misterwolf
  • 424
  • 4
  • 14
  • Why would you need that? In your code just set the variable to be the name you want, or the parameters from the user – j-dexx Nov 09 '15 at 13:14
  • In the methods, I have some instructions that are repeated because they do the same thing: they set an hash with symbol => value. The value is passed by a parameter, instead the name of the symbol is static because it solely depends from the method, and also, the symbol must be different in each method. So I would know if there is something that does an "eval" on the name of variable and consequently to DRY code. Your idea is good ( pass symbol through parameter ) but I wanted to confort myself with others :-) thank you! – misterwolf Nov 09 '15 at 14:40
  • I would suggest posting your code and asking how to make it dry, rather than what you're suggesting. It sounds like you can extract the repeated sections into a method. – j-dexx Nov 09 '15 at 14:45
  • Hi Japed, sorry for late. My question was really simple, I also asked if it would be a good way of programming. But, can i receive a specific answer? That's: it is possible or no? :) thank u! – misterwolf Nov 21 '15 at 12:14

1 Answers1

0

You'd need to use eval(), although I don't know the specific way you'd achieve what you want:

new_var = eval(stack_overflow.to_sym)

Richard Peck
  • 76,116
  • 9
  • 93
  • 147