Search code examples
crystal-lang

Crystal error: undefined method 'member?' for Array


I'm attempting to convert some Ruby code to Crystal.

One of my methods is:

def check_and_pop_arg(match : String, args : Array(String))
  result = args.member?(match)
  args.delete_if{|v| v == match}
  return result
end

The crystal compiler does not like the member? method for Array. It seems that methods is also undefined, and I cannot find the API documentation for the Array class in crystal.

  1. How do I check for membership?
  2. Is there a good source for API documentation that I'm just not finding?

I've tried searching the web, but even using -"crystal reports", I get far too many false positives.


Solution

  • What you looking for is probably includes?. You can find those things in the API docs, in this case Enumerable.

    arr = ["a","b","c"]
    puts arr.includes? "b"
    
    range1 = (0..10)
    puts range1.includes? 6
    puts range1.includes? 13
    
    # a possible solution using your code
    def check_and_pop_arg(match : String, args : Array(String))
      result = args.includes?(match)
      if result
        args.each_index {|i| if args[i] == match; args.delete_at i end }
      end
      result
    end
    
    puts check_and_pop_arg "b", arr
    puts arr
    

    Output

    % crystal run file.cr
    true
    true
    false
    true
    ["a", "c"]