Comment by chao-
#if and #ifTrue are yours if you want them:
class TrueClass
def if = true
def ifTrue = true
end
class FalseClass
def if = false
def ifTrue = false
end
true.if
# => true
false.if
# => false
#if and #ifTrue are yours if you want them:
class TrueClass
def if = true
def ifTrue = true
end
class FalseClass
def if = false
def ifTrue = false
end
true.if
# => true
false.if
# => false
I apologize for my lack of Smalltalk knowledge. As you can imagine, you can do similar in Ruby by defining ifTrue to accept a block, even adding ifTrue on other all objects and defining something similar:
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.problem is not with ifTrue, and not with it's performance, it's easy to do. it is "ifTrue:ifFalse:"
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.
In Smalltalk those methods don't return `true`. They take a block and evaluate it if the boolean receiving the message
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.