Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
使用 YAML.load_file 时是否可以强制 Ruby 调用初始化方法?我想调用该方法以便为我不序列化的实例变量提供值。我知道我可以将代码分解为一个单独的方法并在调用 YAML.load_file 后调用该方法,但我想知道是否有更优雅的方法来处理这个问题。
我不认为你可以。由于您将添加的代码确实特定于要反序列化的类,因此您应该考虑在类中添加该功能。例如,假设Foo您要反序列化的类,您可以添加一个类方法,例如:
Foo
class Foo def self.from_yaml( yaml ) foo = YAML::load( yaml ) # edit the foo object here foo end end myFoo = Foo.from_yaml( "myFoo.yaml" )