gpt4 book ai didi

ruby - 为什么 `defined?` 返回一个字符串或 nil?

转载 作者:太空宇宙 更新时间:2023-11-03 17:06:56 24 4
gpt4 key购买 nike

在 ruby​​ 中,为什么 defined? 会返回一个字符串?大多数其他以 ? 结尾的 ruby​​ 方法返回一个 bool 值。

这是支持功能请求的黑客攻击,还是故意滥用 ruby​​ 约定,为什么?

例子:

defined?(super)
=> "super"

defined?(nil)
=> "nil"

defined?(Object)
=> "constant"

最佳答案

不,这既不是黑客攻击也不是滥用 Ruby 约定。正如 matz 在 ruby-talk 7986 中所写的那样:

The '?' methods ... return either

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

defined? falls into (b).

此外,正如评论者所指出的,defined? 不是一种方法。 Matz 在 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.

关于ruby - 为什么 `defined?` 返回一个字符串或 nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31954172/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com