Created
June 21, 2022 16:07
-
-
Save avosa/8b23ee9754b16807867c290655e132a5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Dynamically creating repetitive methods using Metaprogramming in Ruby | |
class Eat | |
meals = %w(lunch supper breakfast) | |
meals.each do |meal| | |
define_method("#{meal}_meal") do |args| | |
puts "I ate: #{args} for: #{meal}" | |
end | |
end | |
end | |
# Otherwise you would have written above as: | |
class Eat | |
def lunch_meal(args) | |
puts "I ate: #{args} for: lunch" | |
end | |
def supper_meal(args) | |
puts "I ate: #{args} for: supper" | |
end | |
def breakfast_meal(args) | |
puts "I ate: #{args} for: breakfast" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment