Search code examples
crystal-lang

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


I first looked for find as much of the API is the same as Ruby but could not find find. So I thought the next best would be select + first (my array is very small so this would be fine).

Looking at the Crystal API select! for an Array takes a block, in the same way as in Ruby. It appears select! mutates the receiving Array, there is no select (that I can see at least!).

This is my code:

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

The error is:

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

Solution

  • Both Enumerable#find and Enumerable#select exist and are documented on Enumerable.

    Thus something like the following does work as you know it from Ruby:

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

    You can also spare the intermediate array with a regular expression:

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

    And if you replace include? with includes? in your sample code, it actually works too.