Friday, January 06, 2006

Why "undef" is keyword in ruby

undef is a keyword in ruby. But its syntax:
"undef method-name (, method-name)*", looks just like a normal command call (function call without parameter, e.g. print "hello"). Then why not just implement it as a built-in method? As we know, "private", "protected" and "public", which are keywords in lots of other language, are just implemented as plain method in ruby.

What makes "undef" special is in attribute methods. In ruby we can define method like this:

class A
  def a=(value)
    @value = value

And later, we can undefine "a=" with "undef":

undef a=

"a=" is not a valid identifier(because of the '=') unless the parser is expecting a method name, for example, after "alias", "def" or "undef".

Note ":a=" is valid symbol. "private", "protected" and "public" are normal methods since they only accept symbols:

class MyClass

  def method1

  public :method1
  #This is invalid: public method1

Since "undef" is followed by method name, it has to be implemented as a keyword, so the parser/lexer knows when to change its state to accept the extra '='.


Post a Comment

<< Home