Nerd For Tech
Published in

Nerd For Tech

What are Ruby Lambda functions?

Introduction to Lambda’s and their first class status

photo by Fabio Santaniello Bruun via unsplash.com

If you searched for AWS Lambda functions, then you’re in the wrong place. Ruby Lambda functions are their own thing and even though they aren’t as flashy or well know as AWS Lambda’s I’d argue they’re equally important to understand as a Ruby developer. My hope is to convince you of the same in this blog post.

What are lambdas?

If you’re familiar with JavaScript you know that JavaScript treats its’ functions as first class citizens. In case you aren’t, that’s just a fancy way of saying functions can be stored as variables, passed as arguments to other functions and serve as the return value of a function.

Ruby, unlike JavaScript, doesn’t treat its’ functions as first class citizens which limits functionality to a certain extent. In Ruby, lambda’s bridge this gap and allow us to create functions that are treated like first class citizens. This allows us to encapsulate a certain block of code and anything contained in it and use it elsewhere in our application!

Fun fact, in the process of writing this post I discovered that lambda’s aren’t unique to Ruby and are present in most programming languages.

How do you write lambdas?

Now that we’ve gone over what lambdas are let’s take a look at a few ways to define them.

# lambda
1. my_lambda = lambda { puts "Hello from my lambda!" }
# literal lambda
2. my_literal_lambda = ->() { puts "Hello from my literal lambda!" }

Calling your new cool lambda function can be done in any of the following ways.

1. my_lambda.call2. my_lambda.()3. my_lambda.[] # this can also be called as my_lambda[]4. my_lambda.===

What if you want to use arguments?

1. lambda_with_arg = lambda { |name| puts "Hi, my name's #{name}!" }2. literal_lambda_arg = ->(name) { puts "Hi my name's #{name}!" }

You would call these lambdas in the following ways.

1. lambda_with_arg.call("David")2. lambda_with_arg.("David")3. lambda_with_arg["David"]4. lambda_with_arg.==="David"

If you want to use multiple arguments just comma separate them as usual. I’m testing this using Ruby version 3.0.1 and for whatever reason the square brackets [] can only be called with arguments by removing the . separating the lambda name and the square brackets.

Lambdas can also be written as multi-line blocks by using the do-end keywords.

1. multi_line_lambda = lambda do |name|
2. puts "Hello!"
3. puts "What's your name?"
4. puts "My name is #{name}."
5. end

It is possible to write a multi-line lambda with the literal lambda syntax, however the convention is to use the regular lambda keyword for in that scenario for improved readability.

That pretty much covers how to write and call lambdas but I’d be doing you a disservice if I didn’t cover what makes them unique, their first class citizen status.

First class lambdas

We’ve already seen one aspect of lambdas being first class citizens. Each example above uses a variable to store the lambda function. I can’t overstate the importance of this because this is what allows lambda functions to be passed as arguments and returned as values.

Let’s take a look at how to do both of these.

1. def say_hello(first_name, last_name, lambda_arg)2.   name = lambda_arg.call(first_name, last_name)3.   puts "Hello my name is #{name}."4. end5. forward_lambda = lambda do |first, last|6.   return "#{first} #{last}"7. end8.  backwards_lambda = lambda do |first, last|9.    return "#{last}, #{first}"10. end11. say_hello "david", "polcari", forward_lambda12. say_hello "david", "polcari", backwards_lambda=> Hello my name is david polcari. => Hello my name is polcari, david.

As you can see above, we’re able to define a function, create two separate lambdas and store them in variables before passing them both to the same function.

Here’s an example of returning a lambda.

1. def calculate_tax subtotal2.   tax =  (subtotal * 0.0825).round(2)3.   return lambda { puts tax }4. end5. first_tax = calculate_tax(10)6. second_tax = calculate_tax(100)7. first_tax.call8. second_tax.call=> 0.83
=> 8.25

This is really helpful if you want to abstract out some functionality and store it to be used at a later point in the execution of your program.

That pretty much wraps up Ruby lambdas and how to use them. Hopefully you realize how powerful these really are and will be able to implement them in some of your future projects.

As an aside, for those who are curious, a lambda function is actually an instance of the Proc class in Ruby. Check back here in a few weeks for my next post covering the differences between a proc and a lambda in Ruby.

As always leave a comment below letting me know how you use lambda’s in your own projects!

--

--

--

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Recommended from Medium

Repository mirroring (from GitLab to GitHub)

The TERCium 2022

The Importance of a QA Environment

Advanced Profiling and Tracing MySQL Queries

Deploy Django Application on Windows IIS Server

Spring REST Template in Spring STS Part 2

5 Step Process to Programming for Beginners

What is Bluehost Hosting Plans 2022 — Bluehost Hosting

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
David Polcari

David Polcari

Full-Stack Software Developer located in Austin, Texas with a background in Healthcare and Oil & Gas.

More from Medium

React and Rails 7 without Transpiling

Introduction to Ruby on Rails

Using Serializer With Your Ruby on Rails API

Understanding Nested Iteration: a Key to Success in RB101