我可以在函数体中创建Ruby类吗?我似乎得到了错误,告诉我它不被允许,但我认为这应该是因为类太对象了.
class A
def method
class B
end
end
end
这失败了,在方法体内有错误的类定义.如果我们不能,为什么我们不能在方法内创建类?
zed*_*xff 10
您可以创建类,但不能从方法内部分配常量.
这个例子有效:
class A
def a
b = Class.new
def b.xxx
"XXX"
end
b
end
end
a = A.new.a
p a # #<Class:0x7fa74fe6cc58>
p a.xxx # "XXX"
Run Code Online (Sandbox Code Playgroud)
小智 8
您可以从方法中创建类并将它们分配给常量,如下所示
class A
def create_class class_name
new_class = Class.new
new_class.send :define_method, :speak do
"Hi, There"
end
Object.const_set class_name, new_class
end
end
A.new.create_class "Harry"
h = Harry.new
puts h.speak # responds => "Hi, There"
Run Code Online (Sandbox Code Playgroud)
因为与其他许多语言不同,String中的类名只是ruby中的常量.
class A
def method
self.class.const_set :B, Class.new {
def foo
'bar'
end
}
end
end
A.new.method
A::B.new.foo # => 'bar'
Run Code Online (Sandbox Code Playgroud)
但是,为什么要在方法中分配常量?这没有意义:常量是常量,你只能分配给它们一次,这意味着你只能运行一次方法.然后,为什么你要编写一个方法,如果它只会被运行一次,无论如何?
| 归档时间: |
|
| 查看次数: |
4932 次 |
| 最近记录: |