如何转换哈希数组



我正在尝试转换以下哈希数组:

data = [{
k: [{id: 'abc'}, {id: 'bcd'}, {id: 'cde'}]
o: [{id: 'ede'}, {id: 'qpl'}, {id: 'ged'}]
}]

进入这个:

#<Test:0x00005628978c1e30 @k=['abc', 'bcd', 'cde']>>

我这样做了:

class Test
def initialize(sample)
sample.each do |k, v|
self.instance_variable_set("@#{k}", v.is_a?(Array) ? Test.new(v.map do |v| v[:id] end) : v)
end
end
end
test = Test.new(data)
# => #<Test:0x00005628978c1e30 @k=#<Test:0x00005628978c1d90 @abc=nil, @bcd=nil, @cde=nil>>

我也在尝试将哈希(在数据中注释(转换为这样的东西:

#<Test:0x00005628978c1e30 @k=['abc', 'bcd', 'cde'] @o=#<Test:0x00005628978c1e31 @b=['ede', 'qpl'], @id='teq' >>

有谁知道我如何实现这一目标?

给定

data = [{
k: [{id: 'abc'}, {id: 'bcd'}, {id: 'cde'}],
o: [{id: 'ede'}, {id: 'qpl'}, {id: 'ged'}]
}]

您询问是否可以创建类Test的以下实例(开头未显示#,我在第二行末尾插入了逗号(:

<Test:0x00005628978c1e30 @k=['abc', 'bcd', 'cde']
@o=#<Test:0x00005628978c1e31 @b=['ede', 'qpl'],
@id='teq' >>

这似乎是一个奇怪的要求,但可以按如下方式完成。

class Test
end
t = Test.new
#=> #<Test:0x0000000001eb9c58>
t.instance_variable_set("@b", data.first[:o][0,2].flat_map(&:values))
#=> ["ede", "qpl"]
t
#=> #<Test:0x0000000001eb9c58 @b=["ede", "qpl"]>
t.instance_variable_set("@id", 'teq')
#=> "teq"
t.instance_variables
#=> [:@b, :@id]
t
#=> #<Test:0x0000000001eb9c58 @b=["ede", "qpl"], @id="teq">
test = Test.new
#=> #<Test:0x0000000001e9ad58>
test.instance_variable_set("@k", data.first[:k].flat_map(&:values))
#=> ["abc", "bcd", "cde"]
test
#=> #<Test:0x0000000001e9ad58 @k=["abc", "bcd", "cde"]>
test.instance_variable_set("@o", t) 
#=> #<Test:0x0000000001eb9c58 @b=["ede", "qpl"], @id="teq">
test.instance_variables
#=> [:@k, :@o]
test
#=> #<Test:0x0000000001e9ad58 @k=["abc", "bcd", "cde"],
#     @o=#<Test:0x0000000001eb9c58 @b=["ede", "qpl"], @id="teq">>

最新更新