如何检查Ruby中是否认义了变量? 是否有isset
type方法? express
尝试“除非”而不是“若是” ruby
a = "apple" # Note that b is not declared c = nil unless defined? a puts "a is not defined" end unless defined? b puts "b is not defined" end unless defined? c puts "c is not defined" end
使用defined? YourVariable
defined? YourVariable
保持简单傻 ..;) app
请注意“已定义”和“已分配”之间的区别。 less
$ ruby -e 'def f; if 1>2; x=99; end;p x, defined? x; end;f' nil "local-variable"
即便从未分配过,也会定义x! spa
defined?(your_var)
会起做用。 根据你正在作什么,你也能够作像your_var.nil?
这样的事情your_var.nil?
code
使用defined?
关键字( 文档 )。 它将返回带有项目类型的String,若是不存在则返回nil
。 文档
>> a = 1 => 1 >> defined? a => "local-variable" >> defined? b => nil >> defined? nil => "nil" >> defined? String => "constant" >> defined? 1 => "expression"
正如skalee评论的那样:“值得注意的是,设置为nil的变量已初始化。” get
>> n = nil >> defined? n => "local-variable"