Monday, March 09, 2009

Rediscovering ternary operators

Check out this factorial function, now not even error handling can increase my line numbers!

factorial = lambda{|x| x<0 ? 'error':(x==0 ? 1:(1..x).inject{|x,y| x*y })}

This is just what came to mind, it could handle strings as well if you add in another ternary. What's really interesting now is that when you combine ternaries with iterators you have the two major control structures: if statements and for loops. That means you can conceivably create some massively complex functions in just one line. One long incomprehensible line, but one line nonetheless.

Of course, even the most fanatical Ruby developer wouldn't actually do this because the code would look ridiculous.

I think.

No comments: