Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby's defined? operator

Tags:

ruby

I am not quite clear about the operator defined?.

For example:

 defined? var

Why not:

defined? :var
defined? 'var'  ## i think these two ways maybe make more sense

But this operator can also be followed by an expression.

At what stage does this operator execute? At the compile stage, similarly to sizeof(int) in C?

like image 951
ruanhao Avatar asked Jun 25 '13 02:06

ruanhao


Video Answer


1 Answers

In different contexts, you want to check things at different levels of expansion. defined? is for checking verbatim expression. If you do defined? :var or defined? "var", they will always give a truthy value because :var and "var" are valid Ruby expressions (symbol and string).

If you want to check one-level expansion of expressions, then there are specific methods. In this case, if you want to check if such method exists, you can do respond_to? :var or respond_to? "var". If you want to check if such variable exists, then you can do local_variables.key?(:var).

Also, defined? is not just for checking a single token. It is also for checking complex expressions like [1, 2, 3].each{|x| puts x}. It would be inconvenient if you had to express that in a symbol.


The last part of this question is very interesting. Usually, when a method is to be executed, all of its arguments are evaluated in advance (but not the block). For defined?, its argument is not evaluated; it is just parsed. It behaves as if it is taking a block. RDoc says: Note that the expression is not executed. I cannot answer how this is done.
like image 165
sawa Avatar answered Sep 25 '22 03:09

sawa