Introduction
We use def keywords to describe methods, which is acceptable in most situations. However, if you have to develop several techniques, each with the same fundamental structure and logic, it looks repetitive and not at all dry. Ruby allows for the instant creation of methods due to its dynamic nature.
Let's take an example for better understanding:
class A
define_method :a do
puts "hello"
end
define_method :greeting do |message|
puts message
end
end
A.new.a #=> hello
A.new.greeting 'Ninja' #=> Ninja
The above code gives the following output:
Defining Methods with define_method
We can use “define_method” for dynamically creating methods in ruby. The define_method defines a receiver-based instance method. A Proc, a Method, or an UnboundMethod object can be used as the method argument.
Let's see an example of define_method for dynamically creating methods in ruby.
Here is an example of code without define_method.
class User
ONLINE = 0
OFFLINE = 1
PENDING = 2
attr_accessor :status
def online?
status == ONLINE
end
def offline?
status == User::OFFLINE
end
def pending?
status == User::PENDING
end
end
user = User.new
user.status = 1
puts user.offline?
#=> true
puts user.online?
#=> false
The above code gives the following output:
Using the define_method, the above code can be written as:
class User
ONLINE = 0
OFFLINE = 1
PENDING = 2
attr_accessor :status
[:online, :offline, :pending].each do |method|
define_method "#{method}?" do
status == User.const_get(method.upcase)
end
end
end
user = User.new
user.status = 1
puts user.offline?
#=> true
puts user.online?
#=> false
The output of the code above where define_method is used is shown below.