Procedure Object in Ruby

2020-12-16 hit count image

Let's see what the procedure object and how to use it in Ruby.


In this blog post, we’ll see what the procedure object is and how to use the procedure object in Ruby.

Procedure Object

Procedure Object means that the object includes program procedures as data, and you can use proc and lambda for it in Ruby.

Procedure Object is basically stored in the Proc class, and we can use the call method to call the procedures saved in the class.

p = {
  puts 'This is a procedure object'
# This is a procedure object

You can save the Procedure Object like other objects, and pass it via parameters.

p = { |count|
  puts "Counts: #{count}"
# Counts: 2

proc and lambda

porc and lambda have the same features as

  • proc

      p = proc { |count|
        puts "Counts: #{count}"
      # Counts: 2
  • lambda

      p = lambda { |count|
        puts "Counts: #{count}"
      # Counts: 2

However, lambda is more strict than proc and


      p = { |a, b|
        puts "Number: #{a}"
      # Number: 2
  • proc

      p = proc { |a, b|
        puts "Number: #{a}"
      # Number: 2

As above, and proc don’t matter if only one of the two parameters is passed, but the errors occur in lambda like below.

p = lambda { |a, b|
  puts "Number: #{a}"
# index.rb:1:in `block in <main>': wrong number of arguments (given 1, expected 2) (ArgumentError)


In Ruby, if you execute the string enclosed in backquotes(`) at the command prompt, the string will be executed and display the result.

puts `date`
# Wed Sep  2 12:58:05 JST 2020

If you execute eval with string, Ruby will execute the string as a program.

a = 5
b = 10
eval ("puts #{a + b}")
# 15

If the eval receives many procedures, the eval executes only the last one.

a = "1..10; 1..4;"
eval(a).each {|v| puts v}
# 1
# 2
# 3
# 4


We’ve seen what the Procedure Object is and how to use it. Actually, the Procedure Object is not used normally, but it’s useful if you remember it.

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.