Why does `defined?` return a string or nil?

前端 未结 2 1527
耶瑟儿~
耶瑟儿~ 2021-01-25 02:14

In ruby, why would defined? return a string? Most other ruby methods ending with a ? return a boolean.

Was this a hack to support a feature req

相关标签:
2条回答
  • 2021-01-25 02:45

    No, it was neither a hack nor a misuse of Ruby convention. As matz writes in ruby-talk 7986:

    The '?' methods ... return either

    • (a) true or false
    • (b) non-false informative value or nil

    defined? falls into (b).

    Also, as commenters have pointed out, defined? is not a method. Matz expands in ruby-talk 1637:

    [defined? is] a control structure. Not everything is a message send in Ruby, e.g. control structures, variables, blocks are not objects. defined? is among these things.

    0 讨论(0)
  • 2021-01-25 02:58

    As sawa points out defined? is not actually a method.

    If it were, the Ruby source code docs states this is allowed for methods that end in a question mark.

    Methods that end with a question mark by convention return boolean. But they may not always return just true or false. Often they will may return an object to indicate a true value (or “truthy” value).

    ref: https://github.com/ruby/ruby/blob/c8b3f1b470e343e7408ab5883f046b1056d94ccc/doc/syntax/methods.rdoc

    0 讨论(0)
提交回复
热议问题