如何检查一个变量是否在Ruby中定义?是否有isset类型的方法可用?
当前回答
上述语句的正确语法是:
if (defined?(var)).nil? # will now return true or false
print "var is not defined\n".color(:red)
else
print "var is defined\n".color(:green)
end
用变量替换(var)。该语法将返回一个true/false值,用于if语句的计算。
其他回答
试着用“除非”而不是“如果”
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来检查一个特定的字段是否在哈希中设置,可能会产生意想不到的行为:
var = {}
if defined? var['unknown']
puts 'this is unexpected'
end
# will output "this is unexpected"
这里的语法是正确的,但定义?Var ['unknown']将被求值为字符串"method",因此if块将被执行
检查哈希中是否存在键的正确符号是:
if var.key?('unknown')
请注意“定义的”和“指定的”之间的区别。
$ ruby -e 'def f; if 1>2; x=99; end;p x, defined? x; end;f'
nil
"local-variable"
X是定义的,即使它从未被赋值!
定义?(your_var)将工作。取决于你在做什么你也可以做your_var。nil?
使用定义的?YourVariable 保持简单,傻瓜..;)
推荐文章
- 是否可以在MiniTest中运行单个测试?
- 如何在Ruby中生成a和b之间的随机数?
- 无法安装gem -未能建立gem本地扩展-无法加载这样的文件——mkmf (LoadError)
- 如何在Ruby中创建文件
- 什么是Ruby文件。开放模式和选项?
- Ruby数组到字符串的转换
- 如何分割(块)一个Ruby数组成X元素的部分?
- Ruby中“or”和||的区别?
- 如何测试参数是否存在在轨道
- 在Ruby中不创建新字符串而修饰字符串的规范方法是什么?
- RVM不是一个函数,用' RVM use…’不会起作用
- 了解Gemfile。锁文件
- 如何确定一个数组是否包含另一个数组的所有元素
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?
- 最好的打印散列的方法