从数组键初始化Struct

时间:2017-03-21 16:24:05

标签: arrays ruby struct

我有

arrs = [[:key1, key2, key3, key4],[:key6, key7]]

我想通过使用这样的键来定义Struct

arrs.map do |arr|
  Struct.new(arr)
end

但确实会引发错误:

TypeError: no implicit conversion of Array into String
    from (irb):26:in `new'
    from (irb):26

那么,我们有没有办法在Struct中初始化这些键?

1 个答案:

答案 0 :(得分:4)

使用splat运算符:

arrs = [[:key1, :key2, :key3, :key4],[:key6, :key7]]
arrs.map { |a| Struct.new(*a) }
=> [#<Class:0x007fa833e25738>, #<Class:0x007fa833e1fa18>]