-2

I have two questions.

1) I need to create a dynamic structure, whose members are driven through an array. For ex:

    members = [:a, :b]
    Config  = Struct.new(members) #=> Struct.new(:a, :b)
    FlatConfig = Struct.new(members) #=> Struct.new(:a, :b)
    config = Config.new()
    flat = FlatConfig.new()

After some days, If I need to add another member to these struct, then all I need to do is add a member in that members array (memebers = [:a, :b, :c]) and I don't need to tough the code further. Thus I am asking this. How to achieve this?

2) Now I need to build the values of flat Struct members by means of doing some manipulation on config struct member values. For eg:

    config.each{|configMember|
      result = configMember.collect{|c| someArray.collect{|s| s + '--' + y}}
      flat[":#{cofigMember}"] = result #=> Intent is to store result in same member as iterated through  config struct.
    }

How to achieve (1) and (2)?

Thanks in advance.

1 Answer 1

0

For your 1), use the splat operator:

Struct.new(*members)

I don't really understand your second question. Is "how can I access the same variable in two configs"?

config.members.each { |key|
  configMember = config[key]
  # do something
  flat[key] = result
}
2
  • Hi, Thanks for your update. In (2), config and flat structs have different member names (keys). Flat config has same member names as config struct, but with prefix "flat_". Now how to store result to flat struct? Jul 12, 2013 at 9:48
  • flat[:"flat_#{key}"] = result
    – Amadan
    Jul 12, 2013 at 9:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.