DEV Community

Kelly Stannard
Kelly Stannard

Posted on

1

Procable Classes

This is I think a good combination of cheap and simple for use in a more functional style of ruby.

Very simple cases

class AddOne
  singleton_class.attr_accessor :to_proc
  self.to_proc = ->(x) { x + 1 }
  define_singleton_method(:call, to_proc)
end

1.then(&AddOne) #=> 2
AddOne.call(1) #=> 2
Enter fullscreen mode Exit fullscreen mode

More complex cases

Most times you will want to use Object instances as they make refactoring easier.

class AddTwo
  singleton_class.attr_accessor :to_proc
  self.to_proc = ->(x) { new(x).call }
  define_singleton_method(:call, to_proc)

  def initialize(x)
    @x = x
  end
  def call
    @x + 2
  end
end

1.then(&AddTwo) #=> 3
AddTwo.call(1) #=> 3
Enter fullscreen mode Exit fullscreen mode

edit: changed class << self to singleton_class

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post