Ruby is an extremely dynamic language, which means that code can be generated and executed on the fly. This includes the definition of new classes and methods, as well as the overloading of operators. Existing classes can even be reopened and have methods added, removed and redefined.This allows for extremely flexible and efficient coding.
What is Metaprogramming?
Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data, or that do part of the work at compile time that would otherwise be done at runtime. In many cases, this allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation. Or, more simply put: Metaprogramming is writing code that writes code during runtime to make your life easier.
Example:
class Glider def lift(a) puts "Rising and #{a}" end def bank(b) puts "Turning and #{b}" end end class Nomad def initialize(glider) @glider = glider end def do(action) p @glider @glider.send(action,argument = nil) end def do_arg(action, argument) if argument @glider.send(action, argument) else raise NoMethodError.new(action) end end end nomad = Nomad.new(Glider.new) nomad.do("lift") nomad.do("bank")
nomad.do_arg(“lift”, 1) nomad.do_arg(“bank”, 2)
Cheers!!!!!!
Would be waiting for its few example 🙂
hey ram, take a look to example. I hope it will make sense. 🙂