为什么在 Ruby 中`a = a` `nil`? [英] Why is `a = a` `nil` in Ruby?

查看:34
本文介绍了为什么在 Ruby 中`a = a` `nil`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我观看了这个视频.如果 a 未定义,为什么 a = a 的计算结果为 nil?

I watched this video. Why is a = a evaluated to nil if a is not defined?

a = a # => nil
b = c = q = c # => nil

推荐答案

Ruby 解释器在看到赋值时用 nil 初始化一个局部变量.它在执行赋值表达式之前或什至在赋值不可访问时初始化局部变量(如下例所示).这意味着您的代码使用 nil 初始化 a,然后表达式 a = nil 将评估为右侧的值.

Ruby interpreter initializes a local variable with nil when it sees an assignment to it. It initializes the local variable before it executes the assignment expression or even when the assignment is not reachable (as in the example below). This means your code initializes a with nil and then the expression a = nil will evaluate to the right hand value.

a = 1 if false
a.nil? # => true

第一个赋值表达式没有被执行,但是a被初始化为nil.

The first assignment expression is not executed, but a is initialized with nil.

您可以在 Ruby 作业文档.

You can find this behaviour documented in the Ruby assignment documentation.

这篇关于为什么在 Ruby 中`a = a` `nil`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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