`defined?`和`除非`不能按预期工作 [英] `defined?` and `unless` not working as expected

查看:72
本文介绍了`defined?`和`除非`不能按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期望以下代码段:

var = "Not Empty" unless defined? var
var # => nil

返回"Not Empty",但是我得到了nil.为什么会发生这种情况的任何见解?

to return "Not Empty", but I got nil. Any insight into why this is happening?

推荐答案

这是Ruby中我称之为实际WTF的唯一时刻之一.

This is one of the only moments in Ruby I would call actual WTFs.

您必须使用

unless defined? var
  var = :value
end

使用后缀语法,解释器将在内部nil-修改值,以便它可以对变量进行推理,从而使它在检查完成之前就已定义:

With the postfix syntax, the interpreter will internally nil-ify the value so it can reason about the variable, thus making it defined before the check is done:

# Doesn't print anything
unless defined?(foo) and (p(foo) or true)
  foo = :value
end

# Prints nil
bar = :value unless defined?(bar) and (p(bar) or true)

这篇关于`defined?`和`除非`不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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