在 Ruby 中,除非定义,否则为什么不会`foo = true?(foo)` 进行赋值?

编程入门 行业动态 更新时间:2024-10-26 07:32:50
本文介绍了在 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)` 进行赋值?

本文发布于:2023-10-16 15:57:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1498044.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:赋值   定义   Ruby   true   foo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!