Can Ruby really be used as a functional language? What are some good tutorials to teach this facet of the language? Note: I really want to use and stick with Ruby as my primary language so I am not interested at this point in being converted to YAFL (yet another functional language). I am really interested in how well Ruby's functional facets perform against the standard functional language baseline. Thanks.
Yes...sort of. Ruby lacks a reasonable construct to enforce immutability. (Object#freeze
doesn't count) Immutability is really the cornerstone of functional languages. Further, Ruby's core libraries are highly oriented toward imperative design. Its Array
and Hash
classes are both mutable by nature, even String
has methods which make non-immutable (e.g. gsub!
). Ironically, Java is more "functional" than Ruby in this respect.
With that said, it is possible to do functional-like programming in Ruby. Any time you use a block/proc/lambda, you are using a feature that comes from functional programming. Likewise, collection methods like map
and zip
are also higher-order constructs which find their roots in languages like Lisp, ML and Haskell.
If you really want to do functional programming, you will want to use a language which is more geared toward that genre. Some suggestions:
You'll notice that three of these four languages are statically typed. In fact, in the case of Scala and Haskell, these are very statically typed languages (much stronger type systems than, say, Java). I'm not sure why this is a trend in functional languages, but there you have it.
It depends what you mean by "Functional Programming". In my view, the most important thing is that functions are first class values, and in this respect Ruby is a functional language.
It has a fairly comprehensive set of list comprehensions - see Martin Fowler's article. However, it's type system is not as powerful as the likes of Haskell. Also, its focus is not on immutability, as is typical for functional languages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With