Functional ruby
Having written elixir for a while I got curious to see what all can be done in ruby, in a functinoal way mostly in comparison to Elixir. Below are some of the ruby methodologies that I found. I am skipping lambdas and procs for now since they are widely discussed at many places. The snippets are self explanatory.
Splat *
and destructuring a list
Never knew I could deconstruct an array like this.
The above led me to reimagine #map
in a functional way.
Shorthand proc invocation
Ruby has procs and lambdas, for this post we are not digging on those two topics much.
Creating a proc
Creating a lambda
Back to the current section, you would know this:
The above snippet retruns the sum of the elements.
Let’s decrypt (&:+)
&
is shorthand for to_proc
:
is just a symbol notation (Read on ruby symbols)
+
the operator
Now essnetially, you could look at it as & :+
, so a symbol :+
is passed.
Now, as per the definition of to_proc the symbol is called upon the object
itself.
So if you pass a symbol, it is turned into a proc.
Symbol#to_proc
was added to address this common pattern
This then becomes:
Now in order to create a custom functions that we can pass to map we should use a lambda. Lambdas are essentially anonymous functions.
If you are familiar with javascript, you would have used lot of anonymous functions for defining callbacks. On a similar anology we can proceed with a squaring function.
Looks cryptic but you can see that we created an anonymous function and passed
it in with &
.
We could take it out and define the function somewhere else giving
Let’s take a step back now, we just discussed &
essentially calls #to_proc
on it.
Another important thing to remember, if we use a symbol the corresponding method is called on the object itself i.e
Since Integer
doesn’t have a method fn
, it failed.
Hence,
That’s it!
Updated on