如何获得与Crystal中的条件匹配的第一个元素?

Kri*_*ris 2 crystal-lang

我首先寻找find的API与Ruby相同但无法找到find.所以我认为下一个最好的是select+ first(我的数组非常小,所以这样会很好).

查看Crystal的Crystal API select!需要一个块,就像在Ruby中一样.它似乎select!改变了接收阵列,没有select(我至少可以看到!).

这是我的代码:

segment = text.split(' ').select! { |segment| segment.include?("rm_") }.first
Run Code Online (Sandbox Code Playgroud)

错误是:

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

Jon*_*Haß 5

双方Enumerable#findEnumerable#select存在和被证明可枚举.

因此,类似下面的内容可以正常工作,因为您从Ruby中知道它:

segment = text.split(' ').find &.includes?("rm_")
Run Code Online (Sandbox Code Playgroud)

您还可以使用正则表达式来保留中间数组:

segment = text[/rm_[^ ]+/]
Run Code Online (Sandbox Code Playgroud)

如果你更换include?includes?您的示例代码,它确实可以工作了.