如何在 Crystal 中获取符合条件的第一个元素?

How to get the first element matching a criteria in Crystal?

我先找了 find,因为 API 和 Ruby 一样多,但没找到 find。所以我认为下一个最好的是 select + first (我的数组非常小,所以这样就可以了)。

查看数组的 Crystal API select! 需要一个块,与 Ruby 中的方式相同。似乎 select! 改变了接收数组,没有 select (我至少可以看到!)。

这是我的代码:

segment = text.split(' ').select! { |segment| segment.include?("rm_") }.first

错误是:

segment = text.split(' ').select! { |segment| segment.include?("rm_") }.first
                                     ^~~~~~~

Enumerable#findEnumerable#select 都存在并记录在 Enumerable

因此,正如您从 Ruby 了解到的那样,类似下面的内容确实有效:

segment = text.split(' ').find &.includes?("rm_")

你也可以用正则表达式来备用中间数组:

segment = text[/rm_[^ ]+/]

如果您在示例代码中将 include? 替换为 includes?,它实际上也有效。