我最近看到了两种在 Ruby 中使用结构创建类的方法:
Customer = Struct.new(:name, :address) do
# ...
end
class Customer < Struct.new(:name, :address)
# ...
end
这些方法有什么区别?
最佳答案
Ruby 实际上有几个作用域:
# 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 的回答。
关于ruby - 从结构创建类的不同方法之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40818414/