From: timr Date: 2010-11-12T10:20:15+09:00 Subject: Scheme's (cond ((assertion) (value))...(else (value))) statement implemented in ruby? Hi Rubyists, I love ruby, but am learning scheme and kinda like the (cond ((assertion) (value))...(else (value))) syntax for what would normally look like this in ruby: if (assertion 1) value 1 elsif (assertion 2) value 2 else default end I find scheme's cond syntax more quickly digestible since it reads like a table. (cond ((assertion 1) (value 1)) ((assertion 2) (value 2)) (else (default))) So I wondered if I could get a similar looking function in ruby. Here is an attempt: class Object alias l lambda def cond(tests) #acts similar to scheme/LISP cond function using hash #key => value rather than scheme's (cond (assertion)(value)... (else(value))) tests.each_pair do |k,v| if k.call v.call break else next end end end def end_cond; l{true}; end end cond l{3 < 2} => l{ puts "3 is less than 2"}, l{3 > 3} => l{ puts "3 is greater than 3"}, l{3+1 > 4} => l{ puts "4 is greater than 4"}, end_cond => l{ puts "hey, it works!"} # >> hey, it works! I was surprised that the hash seems not to mix-up the order of the k:v pairs like it would if the keys were strings or symbols. I suppose because they are lambda's, the hash doesn't bother alphabetizing them during for the .each_pair method. Since they stay ordered, this table- like if;elsif;else seems to work fine. Can anyone think of any issues to using this approach? Can it give rise to unpredicted values--due to some behind the curtain hash key sorting? Or can anyone come up with a cleaner syntax than a hash of lambdas for both keys and values? I know this is not idiomatic ruby here. I am just having fun.