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

Monday, December 28, 2009

Usually Something, But If...

Which do you prefer to write in Ruby?

if boundary_condition
  code_for_the_extreme_case
else
  code_for_the_typical_case
  ...
end

Or

unless boundary_condition # `if !boundary_condition` as well.
  code_for_the_typical_case
  ...
else
  code_for_the_extreme_case
end

In such cases, first I try to use guards. This is straightforward.

return code_for_the_extreme_case if boundary_condition
code_for_the_typical_case
...

But sometimes I cannot use such notation in cases where not to use return or break.

Solution

I made a DSL for this problem.

class UsuallyPending
  instance_methods.map {|i| i.to_s }.
    reject {|i| /__/ =~ i }.
    each {|m| undef_method m }

  def initialize(b1)
    @b1 = b1
  end

  def but_if(cond, &b2)
    if cond
      b2.call
    else
      @b1.call
    end
  end
end

def usually(&b1)
  UsuallyPending.new(b1)
end

usually do
  p ARGV
  p 'hello!'
end.but_if ARGV.empty? do
  p 'Give me arguments!'
end

This is a straightforward expansion of postpositive if with block instead of a value.

No comments:

Post a Comment

Followers