下面是使用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
外觀如:
01更
[
[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
謝謝鐵皮人 - 這正是我一直在尋找 - 許多感謝 – Scott