如何檢查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"