如何从NilClass实例化nil

时间:2014-09-27 19:17:56

标签: ruby

正如我们所知,(几乎)Ruby中的所有内容都是一个对象,它是一个类的实例 nil也是一个对象:

2.1.3 :016 > nil.object_id
 => 8

它是NilClass

的一个实例
2.1.3 :017 > nil.class
 => NilClass

使用new方法实例化对象。

检查NilClass,我发现它没有new方法:

2.1.3 :021 > NilClass.methods.sort
 => [:!, :!=, :!~, :<, :<=, :<=>, :==, :===, :=~, :>, :>=, :__id__, :__send__, :allocate, :ancestors, :autoload, :autoload?, :class, :class_eval, :class_exec, :class_variable_defined?, :class_variable_get, :class_variable_set, :class_variables, :clone, :const_defined?, :const_get, :const_missing, :const_set, :constants, :define_singleton_method, :display, :dup, :enum_for, :eql?, :equal?, :extend, :freeze, :frozen?, :hash, :include, :include?, :included_modules, :inspect, :instance_eval, :instance_exec, :instance_method, :instance_methods, :instance_of?, :instance_variable_defined?, :instance_variable_get, :instance_variable_set, :instance_variables, :is_a?, :kind_of?, :method, :method_defined?, :methods, :module_eval, :module_exec, :name, :nil?, :object_id, :prepend, :private_class_method, :private_constant, :private_instance_methods, :private_method_defined?, :private_methods, :protected_instance_methods, :protected_method_defined?, :protected_methods, :public_class_method, :public_constant, :public_instance_method, :public_instance_methods, :public_method, :public_method_defined?, :public_methods, :public_send, :remove_class_variable, :remove_instance_variable, :respond_to?, :send, :singleton_class, :singleton_class?, :singleton_method, :singleton_methods, :superclass, :taint, :tainted?, :tap, :to_enum, :to_s, :trust, :untaint, :untrust, :untrusted?] 

现在,出于好奇,如果没有nil方法,NilClass对象如何从new实例化?

2 个答案:

答案 0 :(得分:2)

不是:

<强> NilClass

单身对象的类nil。

http://www.ruby-doc.org/core-2.1.3/NilClass.html

这将使它更清晰:

irb(main):005:0> a = nil
=> nil
irb(main):006:0> b = nil
=> nil
irb(main):007:0> a.object_id
=> 8
irb(main):008:0> b.object_id
=> 8

答案 1 :(得分:1)

Ruby中的一些对象没有实例化,包括;数字,符号,零,真假。拿@ papirtiger的代码并用任何数字或任何符号替换nil,你会看到相同的结果。