views:

158

answers:

2

I've been trying to understand this example Ruby code from a blog entry which says it uses the symbols :DEFAULT, :say and :@message "to look up identifiers". But from what I can tell, it's not looking up the identifiers, but the values associated with those identifiers. I thought identifiers are names of variables, methods, etc. So the identifiers would be "DEFAULT", "say" and "message"? The output of the program is below.

Also, why would you need to look up an identifier?

class Demo
  # The stuff we'll look up.
  DEFAULT = "Hello"
  def initialize
    @message = DEFAULT
  end
  def say() @message end

  # Use symbols to look up identifiers.
  def look_up_with_symbols
    [Demo.const_get(:DEFAULT),
     method(:say),
     instance_variable_get(:@message)]
  end
end

dem = Demo.new
puts dem.look_up_with_symbols

When I run the code I get this output:

Hello
#<Method: Demo#say>
Hello
A: 

Yes, these look up the values of various identifiers.

I'm not sure exactly what you're trying to do, but if you need to translate a symbol (:DEFAULT) to a string ("DEFAULT") use to_s (:DEFAULT.to__s). If you want to look up all the possible identifiers it would depend on what you're looking for.

myobject.methods  # show a list of instance methods an object has (like "say" above)
myobject.instance_variables  # show a list of instance variables an object has (like "@message" above)
myobject.class.constants  # show a list of class level constants (like "DEFAULT" above)

I get the most mileage out of these methods when debugging or trying out new APIs. The only reason I'd probably use these in production code is to output some kind of automatic string representation (XML,HTML,CSV) of an object.

matschaffer
+2  A: 

The sample code uses symbols to get at three things: the value of the DEFAULT const (accessed via :DEFAULT), a method object (accessed via :say), and the value of an instance variable (accessed via :@message). None of the three objects were defined using a symbol, yet you can use symbols to access them.

It's a fairly trivial example. The larger point is that symbols can be used to refer to constants, methods, and instance variables, if for some reason you don't want to refer to them directly via their identifiers. I see this most often used in metaprogramming.

Sarah Mei