Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
1.1.
Code
1.2.
Output
2.
Applying a Function to an Enumerable
3.
Composing Functions
4.
Partially Applying Functions
5.
Memoising Functions
6.
Symbols
7.
Methods
8.
Procs
9.
Frequently Asked Questions
9.1.
Is Ruby functional programming?
9.2.
Do higher-order functions exist in Ruby?
9.3.
Which keyword is used for function?
9.4.
Why do we use functional programming?
9.5.
Do different programming paradigms work with Ruby?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

Functional programming in ruby.

Introduction

Functional Programming in Ruby is a programming paradigm that attempts to bind everything in the form of pure mathematical functions. It's a declarative programming approach. Its primary focus is on "what to solve," instead of an imperative course, which focuses on "how to solve."

Although Ruby is not a functional programming language in the same sense as Lisp and Haskell, its blocks, procs, and lambdas lend themselves well to a functional programming approach. You're programming functionally whenever you use a block with an Enumerable iterator, such as a map or inject.

If the functional programming approach appeals to you, adding functional programming in ruby is simple. The remainder of this blog delves into several options for dealing with functions that show how to implement functional programming in ruby.

You can refer to the documentation of ruby from here.

For example:

Code

Below is the code to show Functional Programming in Ruby

def remove(array, item)

  array.reject! { |v| v == item }
  
end

array = [1,2,3]
remove(array, 1)

# => [2, 3]

array.each do |array|
    puts array
end
You can also try this code with Online Ruby Compiler
Run Code

Output

functional programming in ruby

Applying a Function to an Enumerable

Enumerable defines two of the basic iterators: map and inject. Each anticipates a block. If we are going to develop function-centric applications, we may want methods on our functions that allow us to apply those functions to a specific Enumerable object:

module Functional

def apply(enum)
 enum.map &self
 end
 alias | apply

def reduce(enum)
 enum.inject &self
 end
 alias <= reduce
end

# Add these functional programming methods to 
#Proc and Method classes.

class Proc; include Functional; end
class Method; include Functional; end
You can also try this code with Online Ruby Compiler
Run Code

 

We define methods in a Functional module, which we then include in both the Proc and Method classes. Apply and reduce work for both proc and method objects in this manner. The majority of the ways that follow define methods in this Functional module as well, so they may be used for both Proc and Method.

Composing Functions

When we have two functions, f and g, we may want to construct a new function h, f(g()), or f combined with g. We may build the following technique to do function composition automatically:

module Functional
 
 def compose(f)
 if self.respond_to?(:arity) && self.arity == 1
 lambda {|*args| self[f[*args]] }
 else
 lambda {|*args| self[*f[*args]] }
 end
 end
 
 # * is the natural operator for function composition.
 
 alias * compose
end
You can also try this code with Online Ruby Compiler
Run Code

Partially Applying Functions

Partial application is the act of taking a function and a partial set of argument values and creating a new function that is identical to the original function with the specified arguments fixed in functional programming in ruby. As an example:

product = lambda {|x, y| x*y } # A function of two arguments
double = lambda {|x| product(2,x) } # Apply one argument
You can also try this code with Online Ruby Compiler
Run Code

Memoising Functions

Memoisation is the concept of functional programming in ruby that refers to storing the results of a function call. Memoisation may be beneficial if a function always returns the same value when supplied with the same inputs, if there is reason to expect that the same arguments will be used frequently and if the calculation it performs is rather costly. The following technique may be used to automate memoisation for Proc and Method objects:

module Functional

 def memoize
 cache = {} # An empty cache. The lambda captures this in its closure.
 lambda
 {
 	|*args|
 	unless cache.has_key?(args) # If no cached result for these args
 	cache[args] = self[*args] # Compute and cache the result
 	end
 	cache[args] # Return result from cache
 }
 
 end
 alias +@ memoize # cached_f = +f
end
You can also try this code with Online Ruby Compiler
Run Code

Symbols

"Scalar value objects used as identifiers, translating immutable strings to fixed internal values," according to the Ruby definition. This essentially indicates that symbols are immutable strings. An immutable object cannot be altered in programming.

Because changeable objects can generate flaws that are difficult to identify, symbols' immutability makes them extremely helpful in programming. Because symbols do not change, utilising them helps to prevent this problem.

Methods

A method is a group of statements that execute a specific job and provide the outcome. Methods save time by allowing the user to reuse code without having to retype it.

In Ruby, the method is defined with the def keyword, followed by the method name, and finally with the end keyword. A method must be declared before it may be called, and its name must be lowercase. Methods are simply referred to by their names. When calling a method, just write the name of the method.

Procs

A Proc object is a code encapsulation that may be saved in a local variable, supplied to a method or another Proc, and invoked. Proc is a fundamental idea in Ruby and the foundation of its functional programming in ruby's capabilities.

Frequently Asked Questions

Is Ruby functional programming?

Functional programming is supported by the multi-paradigm language Ruby. Activate this post's status. Ruby (functional, imperative, etc.) is an object-oriented language with support for different paradigms. However, Ruby is an OO language since everything in it is an object.

Do higher-order functions exist in Ruby?

Higher-order functions are one of Ruby's most prevalent functional elements and are essentially used everywhere. Because so many of Ruby's fundamental methods require Blocks, an astonishingly large percentage of them are higher-order functions out of the box.

Which keyword is used for function?

To construct (or define) a function, use the def keyword.

Why do we use functional programming?

Functional programming aims to produce elegant code by utilising language support by employing functions as variables, arguments, and return values. First-class function support has been included in even heavily OOP languages like Java and C# due to first-class functions' flexibility and usefulness.

Do different programming paradigms work with Ruby?

Ruby features just-in-time compilation, trash collection, and dynamic typing. Programming paradigms including procedural, object-oriented, and functional programming are all supported. According to its author, Perl, Smalltalk, Eiffel, Ada, BASIC, and Lisp had an effect on Ruby.

Conclusion

In this article, we have extensively discussed functional programming in ruby.

After reading about the functional programming in ruby, are you not feeling excited to read/explore more articles on the topic of DSA? Don't worry; Coding Ninjas has you covered. To learn, see Try Ruby, the History of Ruby and Constants in Ruby.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass