类的目的是将相似的对象或具有相似行为的对象组合在一起。 1 和 2 非常相似,因此将它们放在同一个类中非常有意义。 true 和 false 然而不相似。事实上,它们的全部意义是它们恰好是相反的,并且具有相反的行为。因此,它们不属于同一类。
您能否举例说明您将在Boolean 类中实现哪种常见行为?我什么都想不出来。
让我们看看TrueClass 和FalseClass 的行为:那里正好有四个 方法。不再。在每种情况下,这两种方法的作用完全相反。您如何以及为什么将其放在一个班级中?
以下是实现所有这些方法的方法:
class TrueClass
def &(other)
other
end
def |(_)
self
end
def ^(other)
!other
end
def to_s
'true'
end
end
现在反过来:
class FalseClass
def &(_)
self
end
def |(other)
other
end
def ^(other)
other
end
def to_s
'false'
end
end
诚然,在 Ruby 中,有很多“魔法”在幕后进行,实际上并没有由 TrueClass 和 FalseClass 处理,而是硬连线到解释器中。 if、&&、|| 和 ! 之类的东西。然而,在 Smalltalk 中,Ruby 借鉴了很多东西,包括 FalseClass 和 TrueClass 的概念,所有这些都被实现为方法,你可以在 Ruby 中做同样的事情:
class TrueClass
def if
yield
end
def ifelse(then_branch=->{}, _=nil)
then_branch.()
end
def unless
end
def unlesselse(_=nil, else_branch=->{})
ifelse(else_branch, _)
end
def and
yield
end
def or
self
end
def not
false
end
end
反过来说:
class FalseClass
def if
end
def ifelse(_=nil, else_branch=->{})
else_branch.()
end
def unless
yield
end
def unlesselse(unless_branch=->{}, _=nil)
ifelse(_, unless_branch)
end
def and
self
end
def or
yield
end
def not
true
end
end
几年前,我写以上内容只是为了好玩,even published it。除了语法看起来不同(因为 Ruby 使用特殊运算符而我只使用方法)之外,它的行为与 Ruby 的内置运算符完全一样。事实上,我实际上服用了the RubySpec conformance testsuite 和ported it over to my syntax,它通过了。