Command-Like Behavior in Ruby Using Procs and Blocks

Introduction to Command-Like Behavior

Welcome to another essential part of our journey into Behavioral Patterns in Ruby programming. In this lesson, we will explore command-like behavior, a technique that is instrumental in promoting flexible and reusable code through Ruby's dynamic features.

You might recall from previous lessons that behavioral design patterns focus on object communication and responsibility distribution within your software. Ruby's command-like behavior encapsulates actions using procs and blocks, allowing users to easily handle queues, requests, and operations in a more fluid and dynamic manner.

What You'll Learn

In this lesson, you will learn how to implement command behavior in Ruby using its dynamic capabilities. We will use modules to define reusable behavior and leverage Ruby's ability to treat methods as first-class objects. Instead of relying on interfaces and concrete classes as in other languages, Ruby allows us to create more fluid and composable solutions.

We will illustrate this with a simple example, starting with a Light class that includes on and off methods, which output messages to the console:

Ruby
# Define a Light class with methods to turn the light on and off
class Light
  # Method to turn the light on
  def on
    puts "Light is on."
  end

  # Method to turn the light off
  def off
    puts "Light is off."
  end
end

Next, we will define command behavior using Ruby’s Proc and create procs that represent turning the light on and off. These procs can be assigned to a simple RemoteControl class to emulate the command pattern:

# Instantiate a new Light object
light = Light.new

# Create a proc to represent turning the light on
light_on = proc { light.on }

# Create a proc to represent turning the light off
light_off = proc { light.off }

# Define a RemoteControl class to set and execute commands
class RemoteControl
  def initialize
    # Initialize with no command set
    @command = nil
  end

  # Method to set the current command
  def set_command(command)
    @command = command
  end

  # Method to execute the command if one is set
  def press_button
    @command.call if @command
  end
end

# Instantiate a new RemoteControl object
remote = RemoteControl.new

# Set the command to turn the light on and execute it
remote.set_command(light_on)
remote.press_button

# Set the command to turn the light off and execute it
remote.set_command(light_off)
remote.press_button
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal