Sonntag, 4. Januar 2009

Implementing if in Ruby the Smalltalk Way

In Smalltalk the if statement is not a keyword, but also a normal message sending to an object. In this case the object receiving the message is a boolean. When a condition is resolved it is either true or false and therefore we can send the messages ifTrue and ifFalse to it.
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: