Skip to content

Instantly share code, notes, and snippets.

@avosa
Created June 21, 2022 16:07
Show Gist options
  • Save avosa/8b23ee9754b16807867c290655e132a5 to your computer and use it in GitHub Desktop.
Save avosa/8b23ee9754b16807867c290655e132a5 to your computer and use it in GitHub Desktop.
# 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