Exploring different ways to pass a function into a method in Ruby

Freya Arakaki
Like coffee, love Ruby, enjoy baking stuff when I am not coding ~♥
Apr 8, 2018 273 words

Hello~ today I will to share a post about different ways of passing functions in Ruby.

There are many ways to pass code around in Ruby, so today I’m going to make a comparison between the 4 different ways. In this post, I will show the syntax of using each of them:

  1. Block
  2. Proc
  3. Lambda
  4. method(:func)

In the next post, I will compare the subtle differences they have.

A quick syntax comparison:

1. using a block

If we have a method call print_it which is expecting a method which takes an argument, like shown below:


def print_it yield "hello world, block" end

Let's try to pass in a method using a block with a do..end syntax:


print_it do |n| puts "***" + n + "***" end


*** hello world, block ***
2. using Proc.new

We'll explore how to use Proc. Let's say we have a method, that is expecting a Proc which takes an argument:


def print_it proc proc.call "hello world, proc" end


print_it(Proc.new do |n| puts "***" + n + "***" end)


*** hello world, proc ***

One difference here is that a Proc can be stored in a variable:


proc = Proc.new do |n| puts "***" + n + "***" end print_it(proc)


*** hello world, proc ***
3. using a Lambda

Now let's learn about how to use lambda, similarly, we begin by having a method like below: ghtly_smiling_face:


def print_it lambda lambda.call "hello world, lambda" end

This is how we pass a lamda into the method:


print_it(lambda do |n| puts "***" + n + "***" end)


*** hello world, lambda ***
4. using method(:some_method)

Again, we start with a method call 🙂


def print_it code code.call "hello world, method" end


def func n puts "***" + n "***" end print_it method(:func)


*** hello world, method ***


4 different ways are discussed in this post about how to pass a function call and how to execute it. In the next post the differences between these methods will be discussed 😄.

Have a nice day~✿~❀ ~!

Written By

Freya Arakaki

Like coffee, love Ruby, enjoy baking stuff when I am not coding ~♥

Enjoyed the post?

Clap to support the author, help others find it, and make your opinion count.


To leave a comment, you need to login first 😉