From: Josh Cheek Date: 2010-11-12T21:42:42+09:00 Subject: Re: Scheme's (cond ((assertion) (value))...(else (value))) statement implemented in ruby? --0016362842dec6b9930494da637c Content-Type: text/plain; charset=ISO-8859-1 On Thu, Nov 11, 2010 at 7:20 PM, timr wrote: > 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! > > How about chaining ternary operators? 3 < 2 ? puts("3 is less than 2") : 3 > 3 ? puts("3 is greater than 3") : 3+1 > 4 ? puts("4 is greater than 4") : puts("hey, it works!") --0016362842dec6b9930494da637c--