0

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?

4
  • 2
    launchctl_list.select { |f| /^(?!- )/.match(f) }.map { |f| f.split(' ').last } is what you want Commented Oct 7, 2016 at 2:15
  • Returns a new array containing all elements of ary for which the given block returns a true value. vs ` Invokes the given block once for each element of self. Creates a new array containing the values returned by the block.` Commented Oct 7, 2016 at 2:17
  • ruby-doc.org/core-2.2.0/Array.html#method-i-map ruby-doc.org/core-2.2.0/Array.html#method-i-select Commented Oct 7, 2016 at 2:17
  • You are confusing Ruby and SQL. What's called SELECT in SQL and a projection in Relational Algebra, is called map in Ruby (and most other languages), collect in Smalltalk (and Ruby), and transform in C++. What Ruby (and Smalltalk) calls select is called WHERE in SQL, a selection or restriction in Relational Algebra, and filter almost anywhere else. Maybe it helps when you consider select's alias find_all. Commented Oct 7, 2016 at 6:52

1 Answer 1

1

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 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.