Returns a hash except the given keys from ENV
and their values.
ENV #=> {"LANG"=>"en_US.UTF-8", "TERM"=>"xterm-256color", "HOME"=>"/Users/rhc"} ENV.except("TERM","HOME") #=> {"LANG"=>"en_US.UTF-8"}
Removes every environment variable; returns ENV:
ENV.replace('foo' => '0', 'bar' => '1') ENV.size # => 2 ENV.clear # => ENV ENV.size # => 0
Yields each environment variable name and its value as a 2-element Array
, returning a Hash
of the names and values for which the block returns a truthy value:
ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2') ENV.select { |name, value| name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"} ENV.filter { |name, value| name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
Returns an Enumerator
if no block given:
e = ENV.select # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:select> e.each { |name, value | name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"} e = ENV.filter # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:filter> e.each { |name, value | name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
Yields each environment variable name and its value as a 2-element Array
, deleting each entry for which the block returns false
or nil
, and returning ENV
if any deletions made, or nil
otherwise:
ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2') ENV.select! { |name, value| name.start_with?('b') } # => ENV ENV # => {"bar"=>"1", "baz"=>"2"} ENV.select! { |name, value| true } # => nil ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2') ENV.filter! { |name, value| name.start_with?('b') } # => ENV ENV # => {"bar"=>"1", "baz"=>"2"} ENV.filter! { |name, value| true } # => nil
Returns an Enumerator
if no block given:
ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2') e = ENV.select! # => #<Enumerator: {"bar"=>"1", "baz"=>"2"}:select!> e.each { |name, value| name.start_with?('b') } # => ENV ENV # => {"bar"=>"1", "baz"=>"2"} e.each { |name, value| true } # => nil ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2') e = ENV.filter! # => #<Enumerator: {"bar"=>"1", "baz"=>"2"}:filter!> e.each { |name, value| name.start_with?('b') } # => ENV ENV # => {"bar"=>"1", "baz"=>"2"} e.each { |name, value| true } # => nil
Yields each environment variable name and its value as a 2-element Array
, returning a Hash
of the names and values for which the block returns a truthy value:
ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2') ENV.select { |name, value| name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"} ENV.filter { |name, value| name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
Returns an Enumerator
if no block given:
e = ENV.select # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:select> e.each { |name, value | name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"} e = ENV.filter # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:filter> e.each { |name, value | name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
Yields each environment variable name and its value as a 2-element Array
, deleting each entry for which the block returns false
or nil
, and returning ENV
if any deletions made, or nil
otherwise:
ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2') ENV.select! { |name, value| name.start_with?('b') } # => ENV ENV # => {"bar"=>"1", "baz"=>"2"} ENV.select! { |name, value| true } # => nil ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2') ENV.filter! { |name, value| name.start_with?('b') } # => ENV ENV # => {"bar"=>"1", "baz"=>"2"} ENV.filter! { |name, value| true } # => nil
Returns an Enumerator
if no block given:
ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2') e = ENV.select! # => #<Enumerator: {"bar"=>"1", "baz"=>"2"}:select!> e.each { |name, value| name.start_with?('b') } # => ENV ENV # => {"bar"=>"1", "baz"=>"2"} e.each { |name, value| true } # => nil ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2') e = ENV.filter! # => #<Enumerator: {"bar"=>"1", "baz"=>"2"}:filter!> e.each { |name, value| name.start_with?('b') } # => ENV ENV # => {"bar"=>"1", "baz"=>"2"} e.each { |name, value| true } # => nil
Returns a Hash
whose keys are the ENV
values, and whose values are the corresponding ENV
names:
ENV.replace('foo' => '0', 'bar' => '1') ENV.invert # => {"1"=>"bar", "0"=>"foo"}
For a duplicate ENV
value, overwrites the hash entry:
ENV.replace('foo' => '0', 'bar' => '0') ENV.invert # => {"0"=>"foo"}
Note that the order of the ENV
processing is OS-dependent, which means that the order of overwriting is also OS-dependent. See About Ordering.
Adds to ENV
each key/value pair in the given hash
; returns ENV:
ENV.replace('foo' => '0', 'bar' => '1') ENV.merge!('baz' => '2', 'bat' => '3') # => {"bar"=>"1", "bat"=>"3", "baz"=>"2", "foo"=>"0"}
Deletes the ENV
entry for a hash value that is nil
:
ENV.merge!('baz' => nil, 'bat' => nil) # => {"bar"=>"1", "foo"=>"0"}
For an already-existing name, if no block given, overwrites the ENV
value:
ENV.merge!('foo' => '4') # => {"bar"=>"1", "foo"=>"4"}
For an already-existing name, if block given, yields the name, its ENV
value, and its hash value; the block’s return value becomes the new name:
ENV.merge!('foo' => '5') { |name, env_val, hash_val | env_val + hash_val } # => {"bar"=>"1", "foo"=>"45"}
Raises an exception if a name or value is invalid (see Invalid Names and Values);
ENV.replace('foo' => '0', 'bar' => '1') ENV.merge!('foo' => '6', :bar => '7', 'baz' => '9') # Raises TypeError (no implicit conversion of Symbol into String) ENV # => {"bar"=>"1", "foo"=>"6"} ENV.merge!('foo' => '7', 'bar' => 8, 'baz' => '9') # Raises TypeError (no implicit conversion of Integer into String) ENV # => {"bar"=>"1", "foo"=>"7"}
Raises an exception if the block returns an invalid name: (see Invalid Names and Values):
ENV.merge!('bat' => '8', 'foo' => '9') { |name, env_val, hash_val | 10 } # Raises TypeError (no implicit conversion of Integer into String) ENV # => {"bar"=>"1", "bat"=>"8", "foo"=>"7"}
Note that for the exceptions above, hash pairs preceding an invalid name or value are processed normally; those following are ignored.
Returns true
when there are no environment variables, false
otherwise:
ENV.clear ENV.empty? # => true ENV['foo'] = '0' ENV.empty? # => false
Returns true
if there is an environment variable with the given name
:
ENV.replace('foo' => '0', 'bar' => '1') ENV.include?('foo') # => true
Returns false
if name
is a valid String
and there is no such environment variable:
ENV.include?('baz') # => false
Returns false
if name
is the empty String
or is a String
containing character '='
:
ENV.include?('') # => false ENV.include?('=') # => false
Raises an exception if name
is a String
containing the NUL character "\0"
:
ENV.include?("\0") # Raises ArgumentError (bad environment variable name: contains null byte)
Raises an exception if name
has an encoding that is not ASCII-compatible:
ENV.include?("\xa1\xa1".force_encoding(Encoding::UTF_16LE)) # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: UTF-16LE)
Raises an exception if name
is not a String:
ENV.include?(Object.new) # TypeError (no implicit conversion of Object into String)
Raises TypeError
, because ENV
is a wrapper for the process-wide environment variables and a clone is useless. Use to_h to get a copy of ENV
data as a hash.
Returns the ARGV
array, which contains the arguments passed to your script, one per element.
For example:
$ ruby argf.rb -v glark.txt ARGF.argv #=> ["-v", "glark.txt"]
Reads the next character from ARGF
and returns it as a String
. Raises an EOFError
after the last character of the last file has been read.
For example:
$ echo "foo" > file $ ruby argf.rb file ARGF.readchar #=> "f" ARGF.readchar #=> "o" ARGF.readchar #=> "o" ARGF.readchar #=> "\n" ARGF.readchar #=> end of file reached (EOFError)
Seeks to offset amount (an Integer
) in the ARGF
stream according to the value of whence. See IO#seek
for further details.
Returns the current filename. “-” is returned when the current file is STDIN.
For example:
$ echo "foo" > foo $ echo "bar" > bar $ echo "glark" > glark $ ruby argf.rb foo bar glark ARGF.filename #=> "foo" ARGF.read(5) #=> "foo\nb" ARGF.filename #=> "bar" ARGF.skip ARGF.filename #=> "glark"
Closes the current file and skips to the next file in ARGV. If there are no more files to open, just closes the current file. STDIN will not be closed.
For example:
$ ruby argf.rb foo bar ARGF.filename #=> "foo" ARGF.close ARGF.filename #=> "bar" ARGF.close
Returns true if the current file has been closed; false otherwise. Use ARGF.close
to actually close the current file.
Parses CSV from a source (String, IO stream, or ARGF
).
Calls the given block with each parsed row:
Without headers, each row is an Array.
With headers, each row is a CSV::Row
.
Generates CSV to an output (String, IO stream, or STDOUT).
Returns the parsed source:
Without headers, an Array of Arrays.
With headers, a CSV::Table
.
When in_string_or_io
is given, but not out_string_or_io
, parses from the given in_string_or_io
and generates to STDOUT.
String input without headers:
in_string = "foo,0\nbar,1\nbaz,2" CSV.filter(in_string) do |row| row[0].upcase! row[1] = - row[1].to_i end # => [["FOO", 0], ["BAR", -1], ["BAZ", -2]]
Output (to STDOUT):
FOO,0 BAR,-1 BAZ,-2
String input with headers:
in_string = "Name,Value\nfoo,0\nbar,1\nbaz,2" CSV.filter(in_string, headers: true) do |row| row[0].upcase! row[1] = - row[1].to_i end # => #<CSV::Table mode:col_or_row row_count:4>
Output (to STDOUT):
Name,Value FOO,0 BAR,-1 BAZ,-2
IO stream input without headers:
File.write('t.csv', "foo,0\nbar,1\nbaz,2") File.open('t.csv') do |in_io| CSV.filter(in_io) do |row| row[0].upcase! row[1] = - row[1].to_i end end # => [["FOO", 0], ["BAR", -1], ["BAZ", -2]]
Output (to STDOUT):
FOO,0 BAR,-1 BAZ,-2
IO stream input with headers:
File.write('t.csv', "Name,Value\nfoo,0\nbar,1\nbaz,2") File.open('t.csv') do |in_io| CSV.filter(in_io, headers: true) do |row| row[0].upcase! row[1] = - row[1].to_i end end # => #<CSV::Table mode:col_or_row row_count:4>
Output (to STDOUT):
Name,Value FOO,0 BAR,-1 BAZ,-2
When both in_string_or_io
and out_string_or_io
are given, parses from in_string_or_io
and generates to out_string_or_io
.
String output without headers:
in_string = "foo,0\nbar,1\nbaz,2" out_string = '' CSV.filter(in_string, out_string) do |row| row[0].upcase! row[1] = - row[1].to_i end # => [["FOO", 0], ["BAR", -1], ["BAZ", -2]] out_string # => "FOO,0\nBAR,-1\nBAZ,-2\n"
String output with headers:
in_string = "Name,Value\nfoo,0\nbar,1\nbaz,2" out_string = '' CSV.filter(in_string, out_string, headers: true) do |row| row[0].upcase! row[1] = - row[1].to_i end # => #<CSV::Table mode:col_or_row row_count:4> out_string # => "Name,Value\nFOO,0\nBAR,-1\nBAZ,-2\n"
IO stream output without headers:
in_string = "foo,0\nbar,1\nbaz,2" File.open('t.csv', 'w') do |out_io| CSV.filter(in_string, out_io) do |row| row[0].upcase! row[1] = - row[1].to_i end end # => [["FOO", 0], ["BAR", -1], ["BAZ", -2]] File.read('t.csv') # => "FOO,0\nBAR,-1\nBAZ,-2\n"
IO stream output with headers:
in_string = "Name,Value\nfoo,0\nbar,1\nbaz,2" File.open('t.csv', 'w') do |out_io| CSV.filter(in_string, out_io, headers: true) do |row| row[0].upcase! row[1] = - row[1].to_i end end # => #<CSV::Table mode:col_or_row row_count:4> File.read('t.csv') # => "Name,Value\nFOO,0\nBAR,-1\nBAZ,-2\n"
When neither in_string_or_io
nor out_string_or_io
given, parses from ARGF
and generates to STDOUT.
Without headers:
# Put Ruby code into a file. ruby = <<-EOT require 'csv' CSV.filter do |row| row[0].upcase! row[1] = - row[1].to_i end EOT File.write('t.rb', ruby) # Put some CSV into a file. File.write('t.csv', "foo,0\nbar,1\nbaz,2") # Run the Ruby code with CSV filename as argument. system(Gem.ruby, "t.rb", "t.csv")
Output (to STDOUT):
FOO,0 BAR,-1 BAZ,-2
With headers:
# Put Ruby code into a file. ruby = <<-EOT require 'csv' CSV.filter(headers: true) do |row| row[0].upcase! row[1] = - row[1].to_i end EOT File.write('t.rb', ruby) # Put some CSV into a file. File.write('t.csv', "Name,Value\nfoo,0\nbar,1\nbaz,2") # Run the Ruby code with CSV filename as argument. system(Gem.ruby, "t.rb", "t.csv")
Output (to STDOUT):
Name,Value FOO,0 BAR,-1 BAZ,-2
Arguments:
Argument in_string_or_io
must be a String or an IO stream.
Argument out_string_or_io
must be a String or an IO stream.
Arguments **options
must be keyword options. See Options for Parsing.
Argument csv_string
, if given, must be a String object; defaults to a new empty String.
Arguments options
, if given, should be generating options. See Options for Generating.
Creates a new CSV object via CSV.new(csv_string, **options)
; calls the block with the CSV object, which the block may modify; returns the String generated from the CSV object.
Note that a passed String is modified by this method. Pass csv_string
.dup if the String must be preserved.
This method has one additional option: :encoding
, which sets the base Encoding
for the output if no no str
is specified. CSV
needs this hint if you plan to output non-ASCII compatible data.
Add lines:
input_string = "foo,0\nbar,1\nbaz,2\n" output_string = CSV.generate(input_string) do |csv| csv << ['bat', 3] csv << ['bam', 4] end output_string # => "foo,0\nbar,1\nbaz,2\nbat,3\nbam,4\n" input_string # => "foo,0\nbar,1\nbaz,2\nbat,3\nbam,4\n" output_string.equal?(input_string) # => true # Same string, modified
Add lines into new string, preserving old string:
input_string = "foo,0\nbar,1\nbaz,2\n" output_string = CSV.generate(input_string.dup) do |csv| csv << ['bat', 3] csv << ['bam', 4] end output_string # => "foo,0\nbar,1\nbaz,2\nbat,3\nbam,4\n" input_string # => "foo,0\nbar,1\nbaz,2\n" output_string.equal?(input_string) # => false # Different strings
Create lines from nothing:
output_string = CSV.generate do |csv| csv << ['foo', 0] csv << ['bar', 1] csv << ['baz', 2] end output_string # => "foo,0\nbar,1\nbaz,2\n"
Raises an exception if csv_string
is not a String object:
# Raises TypeError (no implicit conversion of Integer into String) CSV.generate(0)
possible options elements:
keyword form: :invalid => nil # raise error on invalid byte sequence (default) :invalid => :replace # replace invalid byte sequence :undef => :replace # replace undefined conversion :replace => string # replacement string ("?" or "\uFFFD" if not specified)
Argument path
, if given, must be the path to a file.
Argument io
should be an IO
object that is:
Open for reading; on return, the IO
object will be closed.
Positioned at the beginning. To position at the end, for appending, use method CSV.generate
. For any other positioning, pass a preset StringIO object instead.
Argument mode
, if given, must be a File mode. See Access Modes.
Arguments **options
must be keyword options. See Options for Generating.
This method optionally accepts an additional :encoding
option that you can use to specify the Encoding
of the data read from path
or io
. You must provide this unless your data is in the encoding given by Encoding::default_external
. Parsing will use this to determine how to parse the data. You may provide a second Encoding
to have the data transcoded as it is read. For example,
encoding: 'UTF-32BE:UTF-8'
would read UTF-32BE
data from the file but transcode it to UTF-8
before parsing.
These examples assume prior execution of:
string = "foo,0\nbar,1\nbaz,2\n" path = 't.csv' File.write(path, string)
With no block given, returns a new CSV object.
Create a CSV object using a file path:
csv = CSV.open(path) csv # => #<CSV io_type:File io_path:"t.csv" encoding:UTF-8 lineno:0 col_sep:"," row_sep:"\n" quote_char:"\"">
Create a CSV object using an open File:
csv = CSV.open(File.open(path)) csv # => #<CSV io_type:File io_path:"t.csv" encoding:UTF-8 lineno:0 col_sep:"," row_sep:"\n" quote_char:"\"">
With a block given, calls the block with the created CSV object; returns the block’s return value:
Using a file path:
csv = CSV.open(path) {|csv| p csv} csv # => #<CSV io_type:File io_path:"t.csv" encoding:UTF-8 lineno:0 col_sep:"," row_sep:"\n" quote_char:"\"">
Output:
#<CSV io_type:File io_path:"t.csv" encoding:UTF-8 lineno:0 col_sep:"," row_sep:"\n" quote_char:"\"">
Using an open File:
csv = CSV.open(File.open(path)) {|csv| p csv} csv # => #<CSV io_type:File io_path:"t.csv" encoding:UTF-8 lineno:0 col_sep:"," row_sep:"\n" quote_char:"\"">
Output:
#<CSV io_type:File io_path:"t.csv" encoding:UTF-8 lineno:0 col_sep:"," row_sep:"\n" quote_char:"\"">
Raises an exception if the argument is not a String object or IO object:
# Raises TypeError (no implicit conversion of Symbol into String) CSV.open(:foo)