Ruby if vs end if 表现不同? [英] Ruby if vs end of the line if behave differently?
本文介绍了Ruby if vs end if 表现不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么这段代码不起作用?
Why doesn't this code work?
b if b = true
错误:未定义的局部变量或方法`b'
但这确实是:
if b = true
b
end
它们不应该是一样的吗?
Shouldn't they be the same?
推荐答案
这是一个很好的问题.它与 Ruby 中变量的作用域有关.
This is a very good question. It has to do with the scoping of variables in Ruby.
这是一个 Matz 在 Ruby 错误跟踪器上发布的帖子:
局部变量作用域从上到下,从左到右确定.所以在if修饰符的条件下首先分配的局部变量在if体的左侧无效.这是一个规范.
local variable scope determined up to down, left to right. So a local variable first assigned in the condition of if modifier is not effective in the left side if body. It's a spec.
这篇关于Ruby if vs end if 表现不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文