This page is READ-ONLY. It is generated from the old site.
All timestamps are relative to 2013 (when this page is generated).
If you are looking for TeX support, please go to VietTUG.org

are you.defined?

Ruby cool!
Added by icy almost 2 years ago  »  Votes: 2/2

I was trying to use defined? as a function argument, and I found that I couldn't do that. That's weird. Let's see the first example

1 >> def foobar?; puts "this is a test"; end
2 nil
3 >> define?(foobar?)
4 "method" 
5 >> s = method("foobar?")
6 #<Method: Object#foobar?>
7 >> s.clall
8 this is a test

That's clear. But I can't do a same thing with defined?

1 >> define?(defined?)
2 SyntaxError: compile error
3 (irb):23: syntax error, unexpected ')'
4 >> s = method("defined?")
5 NameError: undefined method `defined?' for class `Object'
6 

Why? Oh, the answer is very simple: defined? isn't a method, it is an operator. I suddendly found the reason after reading this post http://kconrails.com/2010/12/20/rubys-defined-operator/. As an operator, it works like "+", "!", etc. The post also shows that we can't overwrite / redefine it :)

Strange! And fun!


Comments

Added by icy almost 2 years ago

NOTE 1: As defined? is an operator (not a method), you can't overwrite it.
NOTE 2: As defined? is an operator, invoking defined?(eval("Array")) is equivalent of defined?(eval), which returns "method"