我最近看到2种方法如何创建使用结构在Ruby中的一类:从结构创建类的不同方法之间有什么区别?
Customer = Struct.new(:name, :address) do
# ...
end
class Customer < Struct.new(:name, :address)
# ...
end
什么是这些方法之间的区别?
我最近看到2种方法如何创建使用结构在Ruby中的一类:从结构创建类的不同方法之间有什么区别?
Customer = Struct.new(:name, :address) do
# ...
end
class Customer < Struct.new(:name, :address)
# ...
end
什么是这些方法之间的区别?
红宝石实际上有几个范围:
# scope one, opened with `module` keyword
module ...
# scope two, opened with `class` keyword
class ...
end
end
module
,class
其中的一些。
当你正在使用的第一个例子,你能够共享范围访问f
变量,它是非常方便的在某些情况下:
=> f = 1
=> 1
=> Customer = Struct.new(:a) do
=> puts f
=> end
=> 1
=> #<Customer:0x005561498351f8>
随着第二个例子中,你不能访问f
可变变量:
=> f = 1
=> class Customer < Struct.new(:a)
=> puts f
=> end
#> NameError: undefined local variable or method `f' for Customer:Class
祖先链中还有一个区别 - 请参阅@ AndreyDeineko的答案。
有些区别在于祖先连锁店。
第一个例子:
Customer.ancestors
#=> [Customer, Struct, Enumerable, Object, PP::ObjectMixin, Kernel, BasicObject]
第二个例子:
Customer.ancestors
#=> [Customer, #<Class:0x007ff4328dddc0>, Struct, Enumerable, Object, PP::ObjectMixin, Kernel, BasicObject]
所以在第一个例子Customer
的超是一个Struct
类本身,而在第二,它是一个匿名类#<Class:0x007ff4328dddc0>
。
这两个Customer
可以如何访问其定义范围的变量也有区别 - 请参阅@Зеленый的答案。