Search code examples
rubysyntaxidentifier

Does this Ruby code look up identifiers or the values associated with them?


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

Solution

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