by ck45 · 1y ago · 0 comments
class TrueClass
def if = true
def ifTrue = true
end
class FalseClass
def if = false
def ifTrue = false
end
true.if
# => true
false.if
# => false (a > b) ifTrue: [ "do something" ]
EDIT: to clarify what's happening there, `>` is a message sent to `a` that will result in a boolean. The True class and False class both understand the ifTrue: message and `True>>ifTrue:` executes the block whereas `False>>ifTrue:` just throws it away.There's no `if` keyword in the language. Control flow is done purely through polymorphism.
class TrueClass
def ifTrue(&block) = block.call
end
class FalseClass
def ifTrue(&block) = nil
end
class Object
def ifTrue(&block) = block.call
end
class NilClass
def ifTrue(&block) = nil
end
If ck45's core complaint was that this is not baked into the language, I will agree that it is less convenient for lack of a default.It just isn't very fast.
also it is common to do assignments in the "if", and with actual method and blocks scope of the introduced variable would be different and everyone would be tripping on it all the time.