douyingyu5573 2013-02-06 20:54
浏览 14
已采纳

Ruby如何处理未声明的变量而不是php?

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.

  • 写回答

2条回答 默认 最新

  • duangeli1334 2013-02-06 20:58
    关注
    1. Ruby will complain if you use a variable you have not decalred.

    2. In ruby you usually don't enclose an if in { and }, you put an if and end it with end.

    3. false nil and 0 are different things. Your code will complain that x is not defined and will only puts if x is false or nil

    4. In ruby to check if a value is nil you use nil? like so if !x.nil?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致