module DynamicVariableAndConstantCreator
def self.create_in_class(class_name, variable_name, constant_name)
target_class = Object.const_get(class_name) rescue Object.const_set(class_name, Class.new)
target_class.class_eval do
# 创建局部变量,由于是在class_eval块内,该局部变量仅在这个块内有效
local_variable = "局部变量值"
# 创建实例变量
@instance_variable = "实例变量值"
# 创建类变量
@@class_variable = "类变量值"
# 创建常量
const_set(constant_name, "常量值")
end
end
end
# 测试代码
class TestClass1; end
class TestClass2; end
DynamicVariableAndConstantCreator.create_in_class('TestClass1', 'test_variable', 'TEST_CONSTANT')
DynamicVariableAndConstantCreator.create_in_class('TestClass2', 'test_variable', 'TEST_CONSTANT')
# 验证TestClass1的实例变量
test1 = TestClass1.new
puts test1.instance_variable_get(:@instance_variable) # 输出: 实例变量值
# 验证TestClass1的类变量
puts TestClass1.class_variable_get(:@@class_variable) # 输出: 类变量值
# 验证TestClass1的常量
puts TestClass1::TEST_CONSTANT # 输出: 常量值
# 验证TestClass2的实例变量
test2 = TestClass2.new
puts test2.instance_variable_get(:@instance_variable) # 输出: 实例变量值
# 验证TestClass2的类变量
puts TestClass2.class_variable_get(:@@class_variable) # 输出: 类变量值
# 验证TestClass2的常量
puts TestClass2::TEST_CONSTANT # 输出: 常量值
### 对Ruby变量与常量作用域的理解和运用技巧
1. **局部变量**:在Ruby中,局部变量的作用域仅限于其定义所在的块。在`class_eval`块内定义的局部变量仅在这个块内有效,外部无法访问。这在创建临时变量用于特定逻辑计算时非常有用,避免污染外部作用域。
2. **实例变量**:以`@`开头,实例变量的作用域是对象实例。每个对象都有自己独立的一组实例变量,通过`instance_variable_get`和`instance_variable_set`方法可以在外部访问和修改实例变量。在类的方法定义中,可以直接访问和修改当前对象的实例变量。
3. **类变量**:以`@@`开头,类变量的作用域是整个类及其所有子类。所有类的实例共享相同的类变量。类变量通常用于需要在类的所有实例之间共享的状态信息。通过`class_variable_get`和`class_variable_set`方法可以在外部访问和修改类变量。
4. **常量**:常量在Ruby中一旦定义,一般不建议修改(虽然技术上可以修改)。常量的命名规则是首字母大写。常量的作用域取决于其定义的位置。在类或模块内定义的常量,其作用域就在该类或模块内,可以通过类名或模块名加`::`来访问。在顶级作用域定义的常量,直接通过常量名访问。