Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method

CSV.filter

filter(**options) {|row| ... }
filter(in_string, **options) {|row| ... }
filter(in_io, **options) {|row| ... }
filter(in_string, out_string, **options) {|row| ... }
filter(in_string, out_io, **options) {|row| ... }
filter(in_io, out_string, **options) {|row| ... }
filter(in_io, out_io, **options) {|row| ... }

Reads CSV input and writes CSV output.

For each input row:

  • Forms the data into:

    • A CSV::Row object, if headers are in use.

    • An Array of Arrays, otherwise.

  • Calls the block with that object.

  • Appends the block’s return value to the output.

Arguments:

  • CSV source:

    • Argument in_string, if given, should be a String object; it will be put into a new StringIO object positioned at the beginning.

    • Argument in_io, if given, should be an IO object that is open for reading; on return, the IO object will be closed.

    • If neither in_string nor in_io is given, the input stream defaults to ARGF.

  • CSV output:

    • Argument out_string, if given, should be a String object; it will be put into a new StringIO object positioned at the beginning.

    • Argument out_io, if given, should be an IO object that is ppen for writing; on return, the IO object will be closed.

    • If neither out_string nor out_io is given, the output stream defaults to $stdout.

  • Argument options should be keyword arguments.

    • Each argument name that is prefixed with in_ or input_ is stripped of its prefix and is treated as an option for parsing the input. Option input_row_sep defaults to $INPUT_RECORD_SEPARATOR.

    • Each argument name that is prefixed with out_ or output_ is stripped of its prefix and is treated as an option for generating the output. Option output_row_sep defaults to $INPUT_RECORD_SEPARATOR.

    • Each argument not prefixed as above is treated as an option both for parsing the input and for generating the output.

    • See Options for Parsing and Options for Generating.

Example:

Example
in_string = "foo,0\nbar,1\nbaz,2\n"
out_string = ''
CSV.filter(in_string, out_string) do |row|
  row[0] = row[0].upcase
  row[1] *= 4
end
out_string # => "FOO,0000\nBAR,1111\nBAZ,2222\n"
See also .foreach .generate also in 3.3 · 3.2 · 3.1