1

In php, I can comfortably write:

if (x > 100) 
{ 
   method(); 
}

knowing that if x doesn't exist, my program will treat it as a small bump in the road and keep going.

I'm used to php's ultra-lax variable typing and undeclared handling, and wondering what the rules of Ruby are in relation to this.

What is Ruby's default action when you try to evaluate something that isn't declared?

And if I can pepper this in too... does null, zero, and false equal the same thing in Ruby? Would

if(!x)
{
  puts 'works'
}

puts?

I know these are very simple questions, but either they're too obvious for me to catch or I'm using the wrong search phrases.

4

2 回答 2

4
  1. 如果您使用未贴花的变量,Ruby 会抱怨。

  2. 在 ruby​​ 中,您通常不会将一个包含if{and中},而是将其放入if并以 . 结尾end

  3. false nil并且0是不同的东西。您的代码将抱怨x未定义,并且仅putsxisfalsenil

  4. 在红宝石中检查一个值是否像这样nil使用nil?if !x.nil?

于 2013-02-06T20:58:06.580 回答
1

从最后一个问题开始:在红宝石中,零不被视为假,唯一的假值是:nil和显然false。其他一切都是“真实”价值。

注意:我将使用实例变量,因为局部变量没有被实例化是不正常的。

那么为什么这行不通

if @x > 100 
  method()
end

因为>在 ruby​​ 中实际上是一个方法调用,所以如果@x是 nil (未定义的变量),它将引发 aNoMethodError因为 nil 没有定义该方法。

NoMethodError: undefined method `>' for nil:NilClass

所以你可以在你的条件下做的是首先确保@x具有这样的值:

if @x && @x > 100 
  method()
end
于 2013-02-06T21:02:58.957 回答