以下引用Eclair于2008-2-3 17:05:37的发言:
继续otl……
偶米学过专业的编程- -bbb
第一个接触的语言类的东西是那只小海龟,第二个就是RGSS了……
class A
end
class B
end
class C
end
def define_method_for_class(a_class)
method_def = "def hello
p 'Hello'
end"
eval("class #{a_class}; #{method_def}; end")
end
define_method_for_class(A)
define_method_for_class(B)
define_method_for_class(C)
A.new.hello # => "Hello"
B.new.hello # => "Hello"
C.new.hello # => "Hello"
以下引用叶子于2008-2-4 3:39:23的发言:
可以用eval实现
class A
end
class B
end
class C
end
def define_method_for_class(a_class)
method_def = "def hello
p 'Hello'
end"
eval("class #{a_class}; #{method_def}; end")
end
define_method_for_class(A)
define_method_for_class(B)
define_method_for_class(C)
A.new.hello # => "Hello"
B.new.hello # => "Hello"
C.new.hello # => "Hello"
[本贴由作者于 2008-2-4 3:40:20 最后编辑]
以下引用美兽于2008-2-4 5:09:04的发言:
eval与class_eval追加的方法在重载时会消失,感觉标准的方法仍然是利用超类或者模块mixin.
# 反射测试1
class A
end
def define_method_for_class(a_class)
method_def = "def hello
p 'Hello'
end"
eval("class #{a_class}; #{method_def}; end")
end
define_method_for_class(A)
(Marshal.load(Marshal.dump(A.new))).hello # => "Hello"
# 反射测试2
class A
end
module Hello
def hello
p 'Hello'
end
end
A.send(:include, Hello)
A.new.hello # => "Hello"
# 反射测试3
class B
end
B.send(:define_method, :hello){
p 'Hello'
}
B.new.hello # => "Hello"
欢迎光临 Project1 (https://rpg.blue/) | Powered by Discuz! X3.1 |