我正在尝试转换以下哈希数组:
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' >>
有人知道我能做到这一点吗?
答案 0 :(得分:0)
给予
<style>
.row {
display: table;
width: 98%;
min-width: 440px;
border: solid 5px black;
border-top: none;
margin-top: -4px;
}
.left {
width: 150px;
border-right: solid 5px black;
display:table-cell;
background-color: black;
}
.middle {
width:auto;
display:table-cell;
font-size: 9.5pt;
padding-bottom: 20px;
}
.right {
width: 150px;
border-left: solid 5px black;
display:table-cell;
background-color: black;
padding-left: 5px;
overflow: auto;
}
</style>
<div class="row">
<div class="left">
<img alt="" src="/Images/Blue.png" border="0"></img>
</div>
<div class="middle">
Text which should be at the top
</div>
<div class="right">
</div>
</div>
您问是否可以创建类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' >>