解析与操作的可变范围和顺序:在“ if”中分配 [英] Variable scope and order of parsing vs. operations: Assignment in an "if"

查看:66
本文介绍了解析与操作的可变范围和顺序:在“ if”中分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是,在行尾的 if 语句在行首的代码之前进行求值:

My understanding is that the if statements at the end of the line are evaluated before the code at the front of the line:

'never shown' if (false)

并且可以在 if 语句中进行赋值。

And assignment is possible in an if statement.

'shown' if (value = 'dave is king')
value #=> "dave is king"

并且,将不存在的变量分配给创建。不需要预先存在。

And, when a variable that doesn't exist is assigned to, it is created. There is no need for it to exist beforehand. Is this true?

如果所有这些假设都成立,为什么会失败?

If all these assumptions are true, why does this fail?

error_array << error if (error = import_value(value))
#=> undefined local variable or method `error' for

未定义的局部变量或方法 error是否在数组向右推之前分配给错误?我想了解何时对事物进行评估。

It assigned to error before the array push right? I want to understand when things are evaluated.

这确实有效:

if (error = import_value(value))
  error_array << error
end

现在我真的很困惑。

推荐答案

只有当您尝试分配文字值时,如果调用函数,该函数才起作用。

It only happens when you try to assign a literal value, if you call a function it works.

def foo(a)
  a
end

p 'not shown' if(value = foo(false))
p 'shown' if(value = foo(true))

# This outputs a Warning in IRB
p 'shown' if(value = false)
(irb):2: warning: found = in conditional, should be ==

如果打开调试(-d),则表示将会显示有关已使用变量 value

If you turn on debugging (-d) you will see a warning about an used variable value

warning: assigned but unused variable - value

此有效是因为该语句的评估结果为 true 就其而言,允许其之前的代码运行。

This "works" because the statement does evaluate to true as far as if is concerned, allowing the code preceeding it to run.

这里发生的是当if()用作修饰符具有其自己的绑定范围或上下文。因此,在if之外永远都看不到分配,因此执行该分配没有任何意义。这与if控制结构不同,因为if语句采用的块也与赋值在同一范围内,而if修饰符之前的行不在if的范围内。

What is happening here is that if() when used as a modifier has it's own binding scope, or context. So the assignment is never seen outside of the if, and therefore makes no sense to perform. This is different than if the control structure because the block that the if statement takes is also within the same scope as the assignment, whereas the line that preceeded the if modifier is not within the scope of the if.

换句话说,它们不是等价的。

In other words, these are not equivelant.

if a = some(value)
  puts a
end

puts a if(a = some(value))

前者在if范围内具有投入a ,后者具有投入a 超出范围,因此具有不同的绑定(ruby称为上下文)。

The former having puts a within the scope of the if, the latter having puts a outside the scope, and therefore having different bindings(what ruby calls context).

Ruby操作顺序

这篇关于解析与操作的可变范围和顺序:在“ if”中分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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