nil 的 Ruby 用例,相当于 Python None 或 JavaScript undefined [英] Ruby use case for nil, equivalent to Python None or JavaScript undefined

查看:55
本文介绍了nil 的 Ruby 用例,相当于 Python None 或 JavaScript undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby 的 nil 如何在代码中体现?例如,在 Python 中,当默认参数引用另一个参数时,您可能会使用 None 作为默认参数,但在 Ruby 中,您可以引用 arg 列表中的其他参数(请参阅 这个问题).在 JS 中,undefined 弹出的更多,因为你根本无法指定默认参数.你能举例说明 RubyNone 是如何弹出的以及它是如何处理的吗?

How does Ruby's nil manifest in code? For example, in Python you might use None for a default argument when it refers to another argument, but in Ruby you can refer to other arguments in the arg list (see this question). In JS, undefined pops up even more because you can't specify default arguments at all. Can you give an example of how RubyNone pops up and how it's dealt with?

我不只是在寻找一个使用 nil 的例子.最好是一个真正的代码片段,出于某种原因必须使用 nil.

I'm not looking for just an example using nil. Preferably it would be a real code snippet which had to use nil for some reason or other.

推荐答案

Ruby 的 nil 和 Python 的 None 几乎是等价的(它们代表没有价值),但是来自 Python 的人可能会发现令人惊讶的行为.首先,Ruby 在 Python 引发异常的情况下返回 nil:

Ruby's nil and Python's None are pretty much equivalent (they represent the absence of value), but people coming from Python may find surprising behaviors. First, Ruby returns nil in situations Python raises an exception:

访问数组和散列:

[1, 2, 3][999] # nil. But [].fetch(0) raises an IndexError
{"a" => 1, "b" => 2}["nonexistent"] # nil. But {}.fetch("nonexistent") raises an IndexError

实例实例变量:

class MyClass
  def hello
    @thisdoesnotexist
  end
end

MyClass.new.hello #=> nil

第二个值得注意的事实是 nil 是一个有很多方法的对象,你甚至可以将它转换为整数、浮点数或字符串:

The second remarkable fact is that nil is an object with lots of methods, you can even convert it to integer, float or string:

nil.to_i # 0
nil.to_f # 0.0 # But Integer(nil) or Float(nil) raise a TypeError.
nil.to_s # ""

不出所料,一些 Python 程序员倾向于不喜欢这种宽容的行为(我一开始是这样做的),但是一旦你习惯了它就可以了.

Unsurprisingly, some Python programmers tend to dislike this permissive behaviour (I did at first), but it's ok once you are used to it.

我不确定这能回答你的问题,只是我的 2 美分.

I am not sure this answers your question, just my 2 cents.

这篇关于nil 的 Ruby 用例,相当于 Python None 或 JavaScript undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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