group_by
这是用于进行繁重工作的起点:
SNMP_RESPONSE = [
'[name=1.3.6.1.4.1.15248.2.5.1.3.1.1.8650, value=8650 (INTEGER)]',
'[name=1.3.6.1.4.1.15248.2.5.1.3.1.1.8651, value=8651 (INTEGER)]',
'[name=1.3.6.1.4.1.15248.2.5.1.3.1.2.8650, value=QNewsAK (OCTET STRING)]',
'[name=1.3.6.1.4.1.15248.2.5.1.3.1.2.8651, value=QSuite4AK (OCTET STRING)]',
'[name=1.3.6.1.4.1.15248.2.5.1.3.1.3.8650, value=46835255 (INTEGER)]',
'[name=1.3.6.1.4.1.15248.2.5.1.3.1.3.8651, value=11041721 (INTEGER)]',
'[name=1.3.6.1.4.1.15248.2.5.1.3.1.4.8650, value=8442357 (INTEGER)]',
'[name=1.3.6.1.4.1.15248.2.5.1.3.1.4.8651, value=5717570 (INTEGER)]',
'[name=1.3.6.1.4.1.15248.2.5.1.3.1.5.8650, value=0 (INTEGER)]',
'[name=1.3.6.1.4.1.15248.2.5.1.3.1.5.8651, value=0 (INTEGER)]',
]
SNMP_RESPONSE.group_by{ |s| s.split(',').first[/\d+$/] }
返回:
{
"8650" => [
[0] "[name=1.3.6.1.4.1.15248.2.5.1.3.1.1.8650, value=8650 (INTEGER)]",
[1] "[name=1.3.6.1.4.1.15248.2.5.1.3.1.2.8650, value=QNewsAK (OCTET STRING)]",
[2] "[name=1.3.6.1.4.1.15248.2.5.1.3.1.3.8650, value=46835255 (INTEGER)]",
[3] "[name=1.3.6.1.4.1.15248.2.5.1.3.1.4.8650, value=8442357 (INTEGER)]",
[4] "[name=1.3.6.1.4.1.15248.2.5.1.3.1.5.8650, value=0 (INTEGER)]"
],
"8651" => [
[0] "[name=1.3.6.1.4.1.15248.2.5.1.3.1.1.8651, value=8651 (INTEGER)]",
[1] "[name=1.3.6.1.4.1.15248.2.5.1.3.1.2.8651, value=QSuite4AK (OCTET STRING)]",
[2] "[name=1.3.6.1.4.1.15248.2.5.1.3.1.3.8651, value=11041721 (INTEGER)]",
[3] "[name=1.3.6.1.4.1.15248.2.5.1.3.1.4.8651, value=5717570 (INTEGER)]",
[4] "[name=1.3.6.1.4.1.15248.2.5.1.3.1.5.8651, value=0 (INTEGER)]"
]
}
可以进一步操作散列:
groups = SNMP_RESPONSE.group_by{ |s| s.split(',').first[/\d+$/] }
values = groups.map{ |key, ary| ary.map{ |s| s[/value=(\S+)/, 1] } }
values
好像:
[
[0] [
[0] "8650",
[1] "QNewsAK",
[2] "46835255",
[3] "8442357",
[4] "0"
],
[1] [
[0] "8651",
[1] "QSuite4AK",
[2] "11041721",
[3] "5717570",
[4] "0"
]
]
多一点按摩会给出:
puts values.map{ |a| a.join(', ') }
哪个输出:
8650, QNewsAK, 46835255, 8442357, 0
8651, QSuite4AK, 11041721, 5717570, 0