检查变量是否已定义? [英] Checking if a variable is defined?

查看:36
本文介绍了检查变量是否已定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查 Ruby 中是否定义了变量?是否有 isset 类型的方法可用?

How can I check whether a variable is defined in Ruby? Is there an isset-type method available?

推荐答案

使用 defined? 关键字 (文档).它将返回一个带有项目类型的字符串,如果它不存在,则返回 nil.

Use the defined? keyword (documentation). It will return a String with the kind of the item, or nil if it doesn’t exist.

>> a = 1
 => 1
>> defined? a
 => "local-variable"
>> defined? b
 => nil
>> defined? nil
 => "nil"
>> defined? String
 => "constant"
>> defined? 1
 => "expression"

正如 skalee 评论的那样:值得注意的是,设置为 nil 的变量已被初始化."

As skalee commented: "It is worth noting that variable which is set to nil is initialized."

>> n = nil  
>> defined? n
 => "local-variable"

这篇关于检查变量是否已定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆