开发者

How do I create a class which instance can be evaluated as false? [duplicate]

开发者 https://www.devze.com 2023-04-13 07:09 出处:网络
This question already has answers here: How to inherit from NilClass or how to simulate similar function
This question already has answers here: How to inherit from NilClass or how to simulate similar function (3 answers) Closed 9 years ago.

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 putsing it, which implicitly calls to_s.

0

精彩评论

暂无评论...
验证码 换一张
取 消