condition ifTrue: [ doSomething ] ifFalse: [ doSomethingElse ]If the condition is true the first block will be executed, if false the second block will executed.
This can easly be implemented in Ruby by patching the corresponding True- and FalseClass:
class TrueClass
def if_true
yield
self
end
def if_false
self
end
alias if if_true
alias else if_false
end
class FalseClass
def if_true
self
end
def if_false
yield
self
end
alias if if_true
alias else if_false
end
As you can see I always return self, so that we chain the methods.
Now we can write:
i = 5
(i > 3).if_true {puts 'true'}.if_false {puts 'false'}
Using the alias methods we can write it in the more common form:
i = 5
(i > 3).if {puts 'true'}.else {puts 'false'}
or
i = 5 (i > 3).if do puts 'true' end.else do puts 'false' end
Keine Kommentare:
Kommentar veröffentlichen