Sauraus Sauraus - 1 month ago 17
Ruby Question

How to select a match and split a string in ruby?

I need to select and prune an array of strings in Ruby and I have it partially working.

I have array of strings that looks like this:

321 com.apple.storeaccountd.daemon
- com.apple.cmio.AVCAssistant
- com.apple.diskmanagementd
150 com.apple.CodeSigningHelper
- com.apple.tailspind
197 com.apple.sysmond
- com.apple.storeassetd.daemon
160 com.apple.sandboxd


What I need to do is select only those entries that have an integer which the line below does:

launchctl_list.select! { |f| /^(?!- )/.match(f) }


This results in an array that looks like this:

321 com.apple.storeaccountd.daemon
150 com.apple.CodeSigningHelper
197 com.apple.sysmond
160 com.apple.sandboxd


I now just want to retain the 'last' part of each string in the array and I thought the following line would do the trick but doesn't.

launchctl_list.select! { |f| f.split(' ').last }


The strings in the array do not have their numbers dropped, what am I missing?

Answer

The Array#select method will not modify each entry in the list, its used only to select which one to keep based on what the block returns.

What you want to use is Array#map! like this:

launchctl_list.map!{|f| f.split(' ').last }
Comments