2 ms·
Thanks for pointing out the try method (it is important to note that it is avaible to anyone using Active Support, not only Rails apps). It is mildly different
by DanielRibeiro 15y ago
Thanks for pointing out the try method (it is important to note that it is avaible to anyone using Active Support, not only Rails apps).
It is mildly different (syntax mostly). All of these are attempts to recreate the elvis operator tha Groovy[1] (nowadays present as the The Existential Operator in Coffescript[2]) have.
For better chaining, the Maybe monad can be implemented in Ruby[3]. However they really shine on Haskell and Scala because they have, respectively, do notation and for comprehensions, which effectively work (on this restricted case of handling nulls) as a scope were nulls are ignored.
Doing this with ruby is possible, but requires AST metaprogramming[4], which is the sort of thing that LISP macros do (and is quite suitable to accomplish in LISP[6], as it is homoiconic[5], while Ruby isn't).
[1] http://groovy.codehaus.org/Operators#Operators-ElvisOperator%28%3F%3A%29 http://groovy.codehaus.org/Operators#Operators-ElvisOperator...
[2] http://jashkenas.github.com/coffee-script/#operators http://jashkenas.github.com/coffee-script/#operators
[3] http://pretheory.wordpress.com/2008/02/14/the-maybe-monad-in-ruby/ http://pretheory.wordpress.com/2008/02/14/the-maybe-monad-in...
[4] http://metaphysicaldeveloper.wordpress.com/2010/10/31/rubyunderscore-a-bit-of-arc-and-scala-in-ruby/ http://metaphysicaldeveloper.wordpress.com/2010/10/31/rubyun...
[5] http://en.wikipedia.org/wiki/Homoiconicity http://en.wikipedia.org/wiki/Homoiconicity
[6] http://onclojure.com/2009/03/06/a-monad-tutorial-for-clojure-programmers-part-2/ http://onclojure.com/2009/03/06/a-monad-tutorial-for-clojure...
- klochner 15y agoThanks for the links. Some ruby food for thought . . . > x = nil || 5 #behaviorally equivalent to elvis? > [nil,4,3].compact.map(&:to_s) #null-ignored scope
- DanielRibeiro 15y agoYou are welcome. The second line is the essential notion of Maybe monad as a restriction of the Sequence monad (Some of x works like [x] and None works like [], using ruby's [] notation for lists).