Search code examples
arraysfilteringcrystal-lang

Array filtering does not change the array in Crystal


I got a Array of strings where i want to make a statement if something is true filter away this string in my array.

The code

module CrystalTest
    files = ["path/to/file1.ext", "path/to/file2.ext", "path/to/file3.ext"]

    files.reject do |file|
        reject = true
        reject
    end

    print files
end

I expect the result to be Array files.size => 0 in this case becuase i set reject true to each iterration. But i keep getting files => true

edit: added the fule code snippet.


Solution

  • Array#reject returns a new, filtered array. This means you either need to reassign your files variable like so:

    files = files.reject do |file|
    

    Or use Array#reject!, which modifies the array in place, like so:

    files.reject! do |file|