Metaprogramming is a ruby feature that can dynamically modify the language structure, such as the class structure, module structure, and instance variable information.
You can evenProgramAdd and run the newCodeYou do not need to restart your program.
1. This document describes how to use attr_accessor, attr_reader, and attr_writer.
Class person # can contain multiple parameters to automatically generate the getter and setter methods of the parameter attr_accessor: name,: age # only generate the getter method of the parameter attr_reader: height # generate only the setter method of the parameter attr_writer: heightendp = person. newp. name = "Hanks" P. age = 20p. height = 180 puts p. name
2. What is the internal implementation principle?
In Ruby, the implementation of dynamic code is implemented through a series of "eval" methods, commonly used Eval, instance_eval, class_eval, module_eval
Four. Here we will use class_eval (add executable code to the class ). The Code is as follows:
# Add code to the class. The class is the base class of all classes, that is, this operation # will affect all classes. Here is just an example. Use it with caution! Class class # * indicates that the number of parameters can be an array of one or any number of elements def my_attr_accessor (* ARGs) # iterator loop, that is, what kind of argS operations are performed on each parameter. each do | arg | # getter statement. % q indicates that the expression in eval can have multiple rows of self. class_eval % Q {##{ x} dynamically constructs the function name def # {Arg }##{ x} Based on the parameter name. Return # {Arg is constructed dynamically based on the parameter name.} end} # setter statement, self. class_eval ("def # {Arg} = (VAL); {Arg} = val; End") end # usage: class person my_attr_accessor: name ,: ageendp = person. newp. name = "Hanks" P. age = 20 puts p. nameputs p. age
I am not familiar with the differences between the four eval usage. Continue to learn ~~