Ruby - Define Method

A friend shared an article yesterday at the office that mentioned define_method which is something I haven’t used much so I did some exploring.

A common way of defining methods in Ruby goes something like this:

def method_name(param)
  # logic goes here
end

If you have a series of methods where the structure is the same and the only differences are strings from a given set, you could just define other methods, but there’s a more declarative way via define_method.

class Brain
  define_method("process_thinking") do |argument|
    "Thinking about #{argument}."
  end

  define_method("process_dreaming") do |argument|
    "Dreaming about #{argument}."
  end

  define_method("process_feeling_good") do |argument|
    "Feeling good about #{argument}."
  end
end

mind = Brain.new
puts mind.process_thinking("friends")  # => Thinking about friends.
puts mind.process_dreaming("eagles")  # => Dreaming about eagles.
puts mind.process_feeling_good("eating chicken")  # => Feeling good about eating chicken.

The same results can be achieved by also calling it inside of a loop like this:

class Brain
  ["Thinking", "Dreaming", "Feeling_good"].each do |subject|
    define_method("process_#{subject.downcase}") do |argument|
      "#{subject.gsub('_', ' ')} about #{argument}."
    end
  end
end

mind = Brain.new
puts mind.process_thinking("friends")  # => Thinking about friends.
puts mind.process_dreaming("eagles")  # => Dreaming about eagles.
puts mind.process_feeling_good("eating chicken")  # => Feeling good about eating chicken.

Now we have metaprogramming and a more powerful utilization of define_method.

Learn more