【问题标题】:How to select a match and split a string in ruby?如何在 ruby​​ 中选择匹配项并拆分字符串?
【发布时间】: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


【解决方案1】:

Array#select 方法不会修改列表中的每个条目,它仅用于根据块返回的内容选择要保留的条目。

您要使用的是Array#map!像这样:

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

【讨论】:

    猜你喜欢
    • 2018-09-07
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 2011-04-25
    相关资源
    最近更新 更多