在 Ruby 中,除非定义,否则为什么不会`foo = true?(foo)` 进行赋值? [英] In Ruby why won't `foo = true unless defined?(foo)` make the assignment?

查看:23
本文介绍了在 Ruby 中,除非定义,否则为什么不会`foo = true?(foo)` 进行赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是怎么回事?两种形式的除非"有什么微妙的区别?

<代码>>irb(main):001:0>foo = true 除非定义?(foo)=>零irb(main):002:0>除非定义?(fooo) ;foo = 假;结尾=>错误的

谢谢

解决方案

显然,ruby 在解析时创建了局部变量,将它们设置为 nil 所以它是定义的,无论代码是否执行都会这样做与否.

当代码在你的第一行被评估时,它不会执行赋值部分,因为 foo 被设置为 nil.在第二行,因为 fooo 还没有被解析, defined? 返回 nil 让块内的代码执行并分配 foo.

举个例子,你可以试试这个:

如果为假富 = 43结尾定义?富=>局部变量"

本文摘自 ruby​​-forum 的一个论坛帖子.>

What's going on here? What is the subtle difference between the two forms of "unless"?

> irb(main):001:0> foo = true unless defined?(foo)
=> nil 
irb(main):002:0> unless defined?(fooo) ; fooo = false ; end
=> false 

thx

解决方案

Apparently, ruby creates local variable at parse time setting them to nilso it is defined and this is done whether the code is executed or not.

When the code is evaluated at your first line, it doesn't execute the assignment part since foo is set to nil. In the second line, because fooo has not been parsed yet, defined?returns nil letting the code inside the block execute and assign fooo.

As an example you can try this:

if false  
  foo = 43  
end  
defined? foo  
=> "local-variable"

This is taken from a forum post at ruby-forum.

这篇关于在 Ruby 中,除非定义,否则为什么不会`foo = true?(foo)` 进行赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆