General Question

andrew's avatar

How do I see if a Ruby symbol has already been defined?

Asked by andrew (16562points) June 14th, 2008

I’m touching up our capistrano scripts, but my limited Ruby knowledge is frustrating me. Isn’t there some global hash somewhere I can just query? defined? is getting me nowhere.

Observing members: 0 Composing members: 0

3 Answers

phoenyx's avatar

Your question seems a little odd. Can you pastie the code you’re looking at with some comments?

andrew's avatar

@phoenyx:

Ah ha! Your little nudge helped me figure things out. This is yet another problem with learning Ruby through capistrano.

Cap has a set(symbol, arg) method (like set :foo, “bar”) which I naïvely thought was setting the value of the symbol. In reality, it’s creating a hash of symbols => values behind the scenes. Thank you!

paulc's avatar

The Symbol class has a static array of all the defined Symbols. The catch here is that if you were to do something like Symbol.all_symbols.include?(:fluther) the symbol for :fluther is created, added to the symbols table and then returned in the array you’re checking against so you will always get true.

To get around this you can use any? on the array checking for the string representation of your symbol:
Symbol.all_symbols.any? { |sym| sym.to_s == “fluther” }

Using this as an opportunity to ask for smaller fixed-width fonts and block code formatting markup in answers :)

Answer this question

Login

or

Join

to answer.

This question is in the General Section. Responses must be helpful and on-topic.

Your answer will be saved while you login or join.

Have a question? Ask Fluther!

What do you know more about?
or
Knowledge Networking @ Fluther