the 'if' method take 2

i took another shot at using a method for 'if' instead of a language construct.

Here is an example usage with the easy to read ruby block mechanism. name = "Don"

(name == "Don").true? { puts "Hello Don." } # => "Hello Don" (name == "Bob").true? { puts "FAIL" } # => nil

/typo:code

What the block form doesn't allow is a block for the else clause. We can pass two Proc objects instead, though its less readable. name = "Don"

(name == "Don").true?(Proc.new { puts "Good evening Don." }, Proc.new { puts "Who are you?" })

/typo:code

The implementation. class TrueClass def true?(true_proc = nil, false_proc = nil) if true_proc true_proc.call else yield end end end

class FalseClass def true?(true_proc = nil, false_proc = nil) if false_proc false_proc.call end end end

/typo:code

Note this can be extended to Object and NilClass to have similar semantics to 'if' but i think its a good idea to limit the scope of this foreign/unexpected method.

tags: