Ruby Define Method
define_method builds a method while the program runs. It takes a name and a block, and the block becomes the method body.
Three readers from one loop
One loop visits three names in an array. Each name becomes a method that answers with its own word.
class Basket
[:apple, :pear, :plum].each do |name|
define_method name do
"fresh #{name}"
end
end
end
basket = Basket.new
puts basket.apple
puts basket.pear
puts basket.plumGenerated methods with an argument
A generated method can declare a parameter in its block. The caller passes a value just like a written method.
class Greeter
[:hello, :goodbye].each do |word|
define_method word do |name|
"#{word}, #{name}"
end
end
end
greeter = Greeter.new
puts greeter.hello "Ana"
puts greeter.goodbye "Ana"Methods from a hash
A hash can hold the names and the values together. Each pair becomes a method that answers with its stored value.
class Prices
PRICES = { apple: 3, pear: 5 }
PRICES.each do |name, price|
define_method name do
price
end
end
end
prices = Prices.new
puts prices.apple
puts prices.pearExample
class Shirt
[:small, :medium, :large].each do |size|
define_method size do
"Size #{size}"
end
end
end
shirt = Shirt.new
puts shirt.small
puts shirt.largeKey points
- define_method takes a name and a block.
- The block becomes the body of the new method.
- A loop can build several similar methods in one pass.
- A generated method can take arguments like any other method.
- The names can come from an array or a hash.
In this example, one loop builds three methods on the Shirt class. Each name in the array becomes a method. Each method answers with its own size word.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does define_method need to build a method?