The class of the singleton object nil
.
Several of its methods act as operators:
Others act as converters, carrying the concept of nullity to other classes:
While nil
doesn’t have an explicitly defined to_hash method, it can be used in **
unpacking, not adding any keyword arguments.
Another method provides inspection:
Finally, there is this query method:
static VALUE
false_and(VALUE obj, VALUE obj2)
{
return Qfalse;
}
Returns false
:
false & true # => false false & Object.new # => false
Argument object
is evaluated:
false & raise # Raises RuntimeError.
#define case_equal rb_equal
static VALUE
nil_match(VALUE obj1, VALUE obj2)
{
return Qnil;
}
Returns nil
.
This method makes it useful to write:
while gets =~ /re/ # ... end
#define false_xor true_and
Returns false
if object
is nil
or false
, true
otherwise:
nil ^ nil # => false nil ^ false # => false nil ^ Object.new # => true
static VALUE
nil_inspect(VALUE obj)
{
return rb_usascii_str_new2("nil");
}
Returns string 'nil'
:
nil.inspect # => "nil"
static VALUE
rb_true(VALUE obj)
{
return Qtrue;
}
Returns true
. For all other objects, method nil?
returns false
.
static VALUE
nilclass_rationalize(int argc, VALUE *argv, VALUE self)
{
rb_check_arity(argc, 0, 1);
return nilclass_to_r(self);
}
Returns zero as a Rational:
nil.rationalize # => (0/1)
Argument eps
is ignored.
static VALUE
nil_to_a(VALUE obj)
{
return rb_ary_new2(0);
}
Returns an empty Array
.
nil.to_a # => []
static VALUE
nilclass_to_c(VALUE self)
{
return rb_complex_new1(INT2FIX(0));
}
Returns zero as a Complex:
nil.to_c # => (0+0i)
# File tmp/rubies/ruby-3.4.1/nilclass.rb, line 22
def to_f
return 0.0
end
Always returns zero.
nil.to_f #=> 0.0
static VALUE
nil_to_h(VALUE obj)
{
return rb_hash_new();
}
Returns an empty Hash
.
nil.to_h #=> {}
# File tmp/rubies/ruby-3.4.1/nilclass.rb, line 10
def to_i
return 0
end
Always returns zero.
nil.to_i #=> 0
static VALUE
nilclass_to_r(VALUE self)
{
return rb_rational_new1(INT2FIX(0));
}
Returns zero as a Rational:
nil.to_r # => (0/1)
VALUE
rb_nil_to_s(VALUE obj)
{
return rb_cNilClass_to_s;
}
Returns an empty String:
nil.to_s # => ""
#define false_or true_and
Returns false
if object
is nil
or false
, true
otherwise:
nil | nil # => false nil | false # => false nil | Object.new # => true