I want to create a class Nilly
to obtain a "pseudo-nil" object, but I need it to be evaluated开发者_JAVA百科 as boolean false
.
e.g.:
class Nilly; end
n = Nilly.new
puts n ? 'true' : 'false' #=> I want false here
How can I do that?
P.S.: I tried to do class Nilly < NilClass
, but I coudn't use the new
method (it was stripped out in NilClass
).
Boolean logic in Ruby ONLY allows nil
and false
to be falsy
Everything else is truthy
.
There is no way to do this.
May I ask why you want this?
What is special about your Nilly
class?
I suggest you just call it a different way.
class Nilly
def nil?
true
end
end
And use this in your logic
puts n.nil? ? 'false' : 'true'
Override the new method:
class Nilly < NilClass
def Nilly.new
end
end
n = Nilly.new
puts n ? 'true' : 'false' #=> I want false here
Unlike the previous two solutions, this does exactly what you want. n
actually evaluates as nil, without the need to test with a nil?
method. The to_s
solution only works because you are puts
ing it, which implicitly calls to_s
.
精彩评论