ruby metaprogramming 03

本文介绍了Ruby中的元编程技术,包括eval及其变种如instance_eval、module_eval和class_eval的使用方法,以及如何通过class_variables_get、class_variables_set、instance_variable_get、instance_variable_set、const_get和const_set来操作类变量、实例变量和常量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Refer to Metaprogramming in Ruby


eval

String can  execute  as code by eval which is a method of module Kernel.


instance_eval module_eval and class_eval

They are special type of evals.

Objects can use instance_eval to create methods. For classes, methods are class methods. Remember that anonymous class will be created.

module_eval and class_eval operates on classes and modules.  By another word,  they can not call on pure objects.


class_variables_get and class_variables_get

We can get and set class variables out of class.


class_variables

Method class_variables gives us a list of class variables.


instance_variable_get and instance_variable_set

They give us the ability to get and set the instance variable of object out of class.


const_get and const_set

They give us the ability to get and set the const out of class. Using them, we can even create classes in run time.

Object.const_set("Ruby", Class.new)
class_name = Object.const_get("Ruby")
class_name.class_eval do
  def hello
     puts "hello world"
  end
end

r = class_name.new
r.hello
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值