Blogged by Ujihisa. Standard methods of programming and thoughts including Clojure, Vim, LLVM, Haskell, Ruby and Mathematics written by a Japanese programmer. github/ujihisa

Tuesday, May 26, 2009

Something Like Trinary Operator

Ruby has own trinary operator (conditional operator)

p true ? 1 : 2 #=> 1
p false ? 1 : 2 #=> 2

Let's make a something like it by Ruby.

class TrueClass
  def _?(&b)
    Trinary.new(b)
  end
end

class FalseClass
  def _?(&b)
    Trinary.new(nil)
  end
end

class Trinary
  def initialize(x)
    @x = x
  end

  def _(&y)
    @x ? @x.call : y.call
  end
end

p true._? { :a }._ { :b } #=> :a
p false._? { :a }._ { :b } #=> :b

The original idea was from nanki

No comments:

Post a Comment

Followers