End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
CSV.filter
# File tmp/rubies/ruby-3.0.5/lib/csv.rb, line 1052
def filter(input=nil, output=nil, **options)
# parse options for input, output, or both
in_options, out_options = Hash.new, {row_sep: $INPUT_RECORD_SEPARATOR}
options.each do |key, value|
case key.to_s
when /\Ain(?:put)?_(.+)\Z/
in_options[$1.to_sym] = value
when /\Aout(?:put)?_(.+)\Z/
out_options[$1.to_sym] = value
else
in_options[key] = value
out_options[key] = value
end
end
# build input and output wrappers
input = new(input || ARGF, **in_options)
output = new(output || $stdout, **out_options)
# process headers
need_manual_header_output =
(in_options[:headers] and
out_options[:headers] == true and
out_options[:write_headers])
if need_manual_header_output
first_row = input.shift
if first_row
if first_row.is_a?(Row)
headers = first_row.headers
yield headers
output << headers
end
yield first_row
output << first_row
end
end
# read, yield, write
input.each do |row|
yield row
output << row
end
end
Reads CSV input and writes CSV output.
For each input row:
-
Forms the data into:
-
A
CSV::Rowobject, 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 newStringIOobject positioned at the beginning. -
Argument
in_io, if given, should be anIOobject that is open for reading; on return, theIOobject will be closed. -
If neither
in_stringnorin_iois 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 newStringIOobject positioned at the beginning. -
Argument
out_io, if given, should be anIOobject that is ppen for writing; on return, theIOobject will be closed. -
If neither
out_stringnorout_iois given, the output stream defaults to$stdout.
-
-
Argument
optionsshould be keyword arguments.-
Each argument name that is prefixed with
in_orinput_is stripped of its prefix and is treated as an option for parsing the input. Optioninput_row_sepdefaults to$INPUT_RECORD_SEPARATOR. -
Each argument name that is prefixed with
out_oroutput_is stripped of its prefix and is treated as an option for generating the output. Optionoutput_row_sepdefaults 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.
-
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"