1

我注意到 Ruby 的理念是在运行时尽可能多地保持灵活性。

这是一个典型的(据我所知)Ruby 结构定义:

    Person = Struct.new("Person", :name, :address)
    Person.new("John", "Chicago, IL")

我的问题是,当结构字段/成员列表也在运行时定义时,是否可以在运行时定义结构?看起来像这样的东西:

    Person = Struct.new("Person", list_of_structure_fields)
4

2 回答 2

5

你可以只一个数组:

fields = [:name, :address]
Person = Struct.new("Person", *fields)
Person.new("John", "Chicago, IL")
#=> #<struct Struct::Person name="John", address="Chicago, IL">

这使您可以做一些有趣的事情:

person = {name: "John", address: "Chicago, IL"}
Person = Struct.new("Person", *person.keys)
Person.new(*person.values)
#=> #<struct Struct::Person name="John", address="Chicago, IL">
于 2012-06-22T18:22:15.087 回答
3

OpenStruct就是为了做到这一点而设计的:

require 'ostruct'
h = {name: "John", address: "Chicago, IL"}
person = OpenStruct.new(h)
puts person.name #=> John
person.age  = 35 # freely add fields and values 
于 2012-06-22T21:03:53.213 回答