mnguyen1nc
mnguyen1nc

Reputation: 21

Where is define? method defined? I couldn't find any document about it anywhere

Here's the sample codes:

class Square
  def initialize

    if defined?(@@number_of_squares)
      @@number_of_squares += 1
    else
      @@number_of_squares = 1
    end
  end

  def Square.count
    @@number_of_squares
  end
end

Upvotes: 2

Views: 143

Answers (3)

Jörg W Mittag
Jörg W Mittag

Reputation: 369536

defined? is actually not a method but a unary prefix operator (just like !, not, +@ and -@), but without the capability to override it. It wouldn't make sense to override it anyway, since its behavior cannot be implemented in Ruby.

Upvotes: 2

Peter
Peter

Reputation: 132307

defined? is actually a special operator, since it takes input in an unusual way. For example, you can call

defined? puts

and it will tell you "method". You couldn't do this with a normal function.

Upvotes: 3

lbz
lbz

Reputation: 9748

defined? expression tests whether or not expression refers to anything recognizable (literal object, local variable that has been initialized, method name visible from the current scope, etc.). The return value is nil if the expression cannot be resolved. Otherwise, the return value provides information about the expression.

http://www.ruby-doc.org/docs/keywords/1.9/files/keywords_rb.html#M000014

Upvotes: 4

Related Questions