【发布时间】:2017-02-15 22:13:09
【问题描述】:
我需要在 Ruby 中选择和修剪一个字符串数组,并且我让它部分工作。
我的字符串数组看起来像这样:
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
我需要做的是只选择那些具有以下行的整数的条目:
launchctl_list.select! { |f| /^(?!- )/.match(f) }
这会产生一个如下所示的数组:
321 com.apple.storeaccountd.daemon
150 com.apple.CodeSigningHelper
197 com.apple.sysmond
160 com.apple.sandboxd
我现在只想保留数组中每个字符串的“最后”部分,我认为以下行可以解决问题,但没有。
launchctl_list.select! { |f| f.split(' ').last }
数组中的字符串没有删除它们的数字,我错过了什么?
【问题讨论】:
-
launchctl_list.select { |f| /^(?!- )/.match(f) }.map { |f| f.split(' ').last }是你想要的 -
Returns a new array containing all elements of ary for which the given block returns a true value.vs ` 为 self 的每个元素调用一次给定块。创建一个包含块返回值的新数组。` -
您混淆了 Ruby 和 SQL。在 SQL 中称为
SELECT,在关系代数中称为 投影,在 Ruby(和大多数其他语言)中称为map,在 Smalltalk(和 Ruby)中称为collect,在C++。 Ruby(和 Smalltalk)调用select在 SQL 中称为WHERE,在关系代数中称为 选择 或 限制,而在其他任何地方几乎都称为filter。当您考虑select的别名find_all时,它可能会有所帮助。
标签: arrays ruby string split match