如Expressions@Programming Ruby中所述,
如果未定义其参数(可以是任意表达式),则运算符返回,否则返回该参数的描述defined?
。nil
defined? 1 → "expression"
defined? dummy → nil
defined? printf → "method"
defined? String → "constant"
defined? $& → nil
defined? $_ → "global-variable"
defined? Math::PI → "constant"
defined? ( c,d = 1,2 ) → "assignment"
defined? 42.abs → "method"
所以对于类:
ruby-1.9.2-p180 > defined? Person
=> nil
ruby-1.9.2-p180 > class Person
ruby-1.9.2-p180 ?> end
=> nil
ruby-1.9.2-p180 > defined? Person
=> "constant"
对于方法:
ruby-1.9.2-p180 > def cool
ruby-1.9.2-p180 ?> puts "clear"
ruby-1.9.2-p180 ?> end
=> nil
ruby-1.9.2-p180 > defined? cool
=> "method"
在你的情况下,
defined?(options)
正在调用 options 方法并将结果传递给defined?
.
感谢@Stuart,如前所述,它不是真正的方法,而是由method_missing实现的,这里有一点魔力。
所以实际上你不应该期望方法选项被定义,因此得到 nil baz
。