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

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:

method.rb

def print_it yield "hello world, block" end

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

passing_a_block.rb

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

result

*** 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:

  • note: while using a block, we call it using keyword yield, when using a proc, we use .call

method.rb

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

passing_a_proc.rb

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

result

*** hello world, proc ***

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

store_proc_in_a_variable.rb

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

result

*** 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:

  • note: using lambda is the same as proc, we need to use the keyword .call

lambda.rb

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

This is how we pass a lamda into the method:

passing_a_lambda.rb

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

result

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

Again, we start with a method call 🙂

method.rb

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

passing_a_method.rb

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

result

*** hello world, method ***

Summary

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~✿~❀ ~!

/@doryfish
Written By

Freya Arakaki

Like coffee, love Ruby, enjoy baking stuff when I am not coding ~♥
Published in Ruby
Enjoyed the post?

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