Home > other >  Ruby split array into key:value pair
Ruby split array into key:value pair

Time:10-13

So I have a array, where key:value are recorded as single unit. I want to split the array and record key and value as an individual.

Example

array = ["Image loaded:", "RuleName: xx", "UtcTime: xxx", "ProcessGuid: {xxx}", "ProcessId: 884", "Image: C:\\opt\\td-agent\\bin\\ruby.exe", "ImageLoaded: xxx", "FileVersion: -", "Description: -", "Product: -", "Company: -", "OriginalFileName: -", "Hashes: MD5=xxx", "Signed: false", "Signature: -", "SignatureStatus: Unavailable", "User: xx"]

Now given I want to loop it and extract key:value

LOOP THROUGH ARRAY
array[i] = array.split(',',key,value)
print(key)
print(value)

CodePudding user response:

If you want do build a new array with keys and values splited, you can do that:

new_array = array.map {|a| a.split(":")}
new_array[0][0] # First key value
new_array[0][1] # First value
  • Related