我有
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
中初始化这些键?
答案 0 :(得分:4)
使用splat运算符:
arrs = [[:key1, :key2, :key3, :key4],[:key6, :key7]]
arrs.map { |a| Struct.new(*a) }
=> [#<Class:0x007fa833e25738>, #<Class:0x007fa833e1fa18>]