Metaprogramming IN RUBY

Source: Internet
Author: User

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 ~~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.