Opens the file named by filename
according to the given mode
and returns a new File
object.
See IO.new
for a description of mode
and opt
.
If a file is being created, permission bits may be given in perm
. These mode and permission bits are platform dependent; on Unix systems, see open(2) and chmod(2) man pages for details.
The new File
object is buffered mode (or non-sync mode), unless filename
is a tty. See IO#flush
, IO#fsync
, IO#fdatasync
, and IO#sync=
about sync mode.
f = File.new("testfile", "r") f = File.new("newfile", "w+") f = File.new("newfile", File::CREAT|File::TRUNC|File::RDWR, 0644)
Creates a new Enumerator
object, which can be used as an Enumerable
.
Iteration is defined by the given block, in which a “yielder” object, given as block parameter, can be used to yield a value by calling the yield
method (aliased as <<
):
fib = Enumerator.new do |y| a = b = 1 loop do y << a a, b = b, a + b end end fib.take(10) # => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
The optional parameter can be used to specify how to calculate the size in a lazy fashion (see Enumerator#size
). It can either be a value or a callable object.
Construct a new Exception
object, optionally passing in a message.
Create a new SystemExit
exception with the given status and message. Status is true, false, or an integer. If status is not given, true is used.
Construct a new SignalException
object. sig_name
should be a known signal name.
Construct a new KeyError
exception with the given message, receiver and key.
Construct a SyntaxError
exception.
Construct a new NameError
exception. If given the name parameter may subsequently be examined using the NameError#name
method. receiver parameter allows to pass object in context of which the error happened. Example:
[1, 2, 3].method(:rject) # NameError with name "rject" and receiver: Array [1, 2, 3].singleton_method(:rject) # NameError with name "rject" and receiver: [1, 2, 3]
Construct a NoMethodError
exception for a method of the given name called with the given arguments. The name may be accessed using the name
method on the resulting object, and the arguments using the args
method.
If private argument were passed, it designates method was attempted to call in private context, and can be accessed with private_call?
method.
receiver argument stores an object whose method was called.
Construct a new FrozenError
exception. If given the receiver parameter may subsequently be examined using the FrozenError#receiver
method.
a = [].freeze raise FrozenError.new("can't modify frozen array", receiver: a)
Construct a new NoMatchingPatternKeyError
exception with the given message, matchee and key.
If errno corresponds to a known system error code, constructs the appropriate Errno
class for that error, otherwise constructs a generic SystemCallError
object. The error number is subsequently available via the errno
method.
Creates a new anonymous module. If a block is given, it is passed the module object, and the block is evaluated in the context of this module like module_eval
.
fred = Module.new do def meth1 "hello" end def meth2 "bye" end end a = "my string" a.extend(fred) #=> "my string" a.meth1 #=> "hello" a.meth2 #=> "bye"
Assign the module to a constant (name starting uppercase) if you want to treat it like a regular module.
Create a new CGI
instance.
tag_maker
This is the same as using the options_hash
form with the value { :tag_maker => tag_maker }
Note that it is recommended to use the options_hash
form, since it also allows you specify the charset you will accept.
options_hash
A Hash
that recognizes three options:
:accept_charset
specifies encoding of received query string. If omitted, @@accept_charset
is used. If the encoding is not valid, a CGI::InvalidEncoding
will be raised.
Example. Suppose @@accept_charset
is “UTF-8”
when not specified:
cgi=CGI.new # @accept_charset # => "UTF-8"
when specified as “EUC-JP”:
cgi=CGI.new(:accept_charset => "EUC-JP") # => "EUC-JP"
:tag_maker
String
that specifies which version of the HTML generation methods to use. If not specified, no HTML generation methods will be loaded.
The following values are supported:
HTML 3.x
HTML 4.0
HTML 4.0 Transitional
HTML 4.0 with Framesets
HTML 5
:max_multipart_length
Specifies maximum length of multipart data. Can be an Integer
scalar or a lambda, that will be evaluated when the request is parsed. This allows more complex logic to be set when determining whether to accept multipart data (e.g. consult a registered users upload allowance)
Default is 128 * 1024 * 1024 bytes
cgi=CGI.new(:max_multipart_length => 268435456) # simple scalar cgi=CGI.new(:max_multipart_length => -> {check_filesystem}) # lambda
block
If provided, the block is called when an invalid encoding is encountered. For example:
encoding_errors={} cgi=CGI.new(:accept_charset=>"EUC-JP") do |name,value| encoding_errors[name] = value end
Finally, if the CGI
object is not created in a standard CGI
call environment (that is, it can’t locate REQUEST_METHOD in its environment), then it will run in “offline” mode. In this mode, it reads its parameters from the command line or (failing that) from standard input. Otherwise, cookies and other parameters are parsed automatically from the standard CGI
locations, which varies according to the REQUEST_METHOD.
Creates a DateTime
object denoting the given calendar date.
DateTime.new(2001,2,3) #=> #<DateTime: 2001-02-03T00:00:00+00:00 ...> DateTime.new(2001,2,3,4,5,6,'+7') #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...> DateTime.new(2001,-11,-26,-20,-55,-54,'+7') #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...>
Returns a new Time object based on the given arguments.
With no positional arguments, returns the value of Time.now
:
Time.new # => 2021-04-24 17:27:46.0512465 -0500
Otherwise, returns a new Time object based on the given parameters:
Time.new(2000) # => 2000-01-01 00:00:00 -0600 Time.new(2000, 12, 31, 23, 59, 59.5) # => 2000-12-31 23:59:59.5 -0600 Time.new(2000, 12, 31, 23, 59, 59.5, '+09:00') # => 2000-12-31 23:59:59.5 +0900
Parameters:
year
: an integer year.
month
: a month value, which may be:
An integer month in the range 1..12
.
A 3-character string that matches regular expression /jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec/i
.
day
: an integer day in the range 1..31
(less than 31 for some months).
hour
: an integer hour in the range 0..23
.
min
: an integer minute in the range 0..59
.
sec
is the number of seconds (Integer
, Float
, or Rational
) in the range 0..60
.
zone
: a timezone, which may be:
A string offset from UTC.
A single letter offset from UTC, in the range 'A'..'Z'
, 'J'
(the so-called military timezone) excluded.
An integer number of seconds.
A timezone object; see Timezone Argument for details.
in: zone
: a timezone zone, which may be as above.
Struct.new
returns a new subclass of Struct
. The new subclass:
May be anonymous, or may have the name given by class_name
.
May have members as given by member_names
.
May have initialization via ordinary arguments (the default) or via keyword arguments (if keyword_init: true
is given).
The new subclass has its own method ::new
; thus:
Foo = Struct.new('Foo', :foo, :bar) # => Struct::Foo f = Foo.new(0, 1) # => #<struct Struct::Foo foo=0, bar=1>
Class Name
With string argument class_name
, returns a new subclass of Struct
named Struct::class_name
:
Foo = Struct.new('Foo', :foo, :bar) # => Struct::Foo Foo.name # => "Struct::Foo" Foo.superclass # => Struct
Without string argument class_name
, returns a new anonymous subclass of Struct
:
Struct.new(:foo, :bar).name # => nil
Block
With a block given, the created subclass is yielded to the block:
Customer = Struct.new('Customer', :name, :address) do |new_class| p "The new subclass is #{new_class}" def greeting "Hello #{name} at #{address}" end end # => Struct::Customer dave = Customer.new('Dave', '123 Main') dave # => #<struct Struct::Customer name="Dave", address="123 Main"> dave.greeting # => "Hello Dave at 123 Main"
Output, from Struct.new
:
"The new subclass is Struct::Customer"
Member Names
Symbol arguments member_names
determines the members of the new subclass:
Struct.new(:foo, :bar).members # => [:foo, :bar] Struct.new('Foo', :foo, :bar).members # => [:foo, :bar]
The new subclass has instance methods corresponding to member_names
:
Foo = Struct.new('Foo', :foo, :bar) Foo.instance_methods(false) # => [:foo, :bar, :foo=, :bar=] f = Foo.new # => #<struct Struct::Foo foo=nil, bar=nil> f.foo # => nil f.foo = 0 # => 0 f.bar # => nil f.bar = 1 # => 1 f # => #<struct Struct::Foo foo=0, bar=1>
Singleton Methods
A subclass returned by Struct.new
has these singleton methods:
Method ::new
creates an instance of the subclass:
Foo.new # => #<struct Struct::Foo foo=nil, bar=nil> Foo.new(0) # => #<struct Struct::Foo foo=0, bar=nil> Foo.new(0, 1) # => #<struct Struct::Foo foo=0, bar=1> Foo.new(0, 1, 2) # Raises ArgumentError: struct size differs
Method ::[]
is an alias for method ::new
.
Method :inspect
returns a string representation of the subclass:
Foo.inspect # => "Struct::Foo"
Method ::members
returns an array of the member names:
Foo.members # => [:foo, :bar]
Keyword Argument
By default, the arguments for initializing an instance of the new subclass are ordinary arguments (not keyword arguments). With optional keyword argument keyword_init: true
, the new subclass is initialized with keyword arguments:
# Without keyword_init: true. Foo = Struct.new('Foo', :foo, :bar) Foo # => Struct::Foo Foo.new(0, 1) # => #<struct Struct::Foo foo=0, bar=1> # With keyword_init: true. Bar = Struct.new(:foo, :bar, keyword_init: true) Bar # => # => Bar(keyword_init: true) Bar.new(bar: 1, foo: 0) # => #<struct Bar foo=0, bar=1>
Returns a new IO
object (a stream) for the given integer file descriptor fd
and mode
string. opt
may be used to specify parts of mode
in a more readable fashion. See also IO.sysopen
and IO.for_fd
.
IO.new
is called by various File
and IO
opening methods such as IO::open
, Kernel#open
, and File::open
.
When mode
is an integer it must be combination of the modes defined in File::Constants
(File::RDONLY
, File::WRONLY|File::CREAT
). See the open(2) man page for more information.
When mode
is a string it must be in one of the following forms:
fmode fmode ":" ext_enc fmode ":" ext_enc ":" int_enc fmode ":" "BOM|UTF-*"
fmode
is an IO
open mode string, ext_enc
is the external encoding for the IO
and int_enc
is the internal encoding.
IO
Open Mode Ruby allows the following open modes:
"r" Read-only, starts at beginning of file (default mode). "r+" Read-write, starts at beginning of file. "w" Write-only, truncates existing file to zero length or creates a new file for writing. "w+" Read-write, truncates existing file to zero length or creates a new file for reading and writing. "a" Write-only, each write call appends data at end of file. Creates a new file for writing if file does not exist. "a+" Read-write, each write call appends data at end of file. Creates a new file for reading and writing if file does not exist.
The following modes must be used separately, and along with one or more of the modes seen above.
"b" Binary file mode Suppresses EOL <-> CRLF conversion on Windows. And sets external encoding to ASCII-8BIT unless explicitly specified. "t" Text file mode
The exclusive access mode (“x”) can be used together with “w” to ensure the file is created. Errno::EEXIST is raised when it already exists. It may not be supported with all kinds of streams (e.g. pipes).
When the open mode of original IO
is read only, the mode cannot be changed to be writable. Similarly, the open mode cannot be changed from write only to readable.
When such a change is attempted the error is raised in different locations according to the platform.
IO
Encoding
When ext_enc
is specified, strings read will be tagged by the encoding when reading, and strings output will be converted to the specified encoding when writing.
When ext_enc
and int_enc
are specified read strings will be converted from ext_enc
to int_enc
upon input, and written strings will be converted from int_enc
to ext_enc
upon output. See Encoding
for further details of transcoding on input and output.
If “BOM|UTF-8”, “BOM|UTF-16LE” or “BOM|UTF16-BE” are used, Ruby checks for a Unicode BOM in the input document to help determine the encoding. For UTF-16 encodings the file open mode must be binary. When present, the BOM is stripped and the external encoding from the BOM is used. When the BOM is missing the given Unicode encoding is used as ext_enc
. (The BOM-set encoding option is case insensitive, so “bom|utf-8” is also valid.)
opt
can be used instead of mode
for improved readability. The following keys are supported:
Same as mode
parameter
Specifies file open flags as integer. If mode
parameter is given, this parameter will be bitwise-ORed.
External encoding for the IO
.
Internal encoding for the IO
. “-” is a synonym for the default internal encoding.
If the value is nil
no conversion occurs.
Specifies external and internal encodings as “extern:intern”.
If the value is truth value, same as “t” in argument mode
.
If the value is truth value, same as “b” in argument mode
.
If the value is false
, the fd
will be kept open after this IO
instance gets finalized.
Also, opt
can have same keys in String#encode
for controlling conversion between the external encoding and the internal encoding.
fd = IO.sysopen("/dev/tty", "w") a = IO.new(fd,"w") $stderr.puts "Hello" a.puts "World"
Produces:
Hello World
require 'fcntl' fd = STDERR.fcntl(Fcntl::F_DUPFD) io = IO.new(fd, mode: 'w:UTF-16LE', cr_newline: true) io.puts "Hello, World!" fd = STDERR.fcntl(Fcntl::F_DUPFD) io = IO.new(fd, mode: 'w', cr_newline: true, external_encoding: Encoding::UTF_16LE) io.puts "Hello, World!"
Both of above print “Hello, World!” in UTF-16LE to standard error output with converting EOL generated by puts
to CR.
Creates a new OpenStruct
object. By default, the resulting OpenStruct
object will have no attributes.
The optional hash
, if given, will generate attributes and values (can be a Hash
, an OpenStruct
or a Struct
). For example:
require "ostruct" hash = { "country" => "Australia", :capital => "Canberra" } data = OpenStruct.new(hash) data # => #<OpenStruct country="Australia", capital="Canberra">
Returns a new range based on the given objects begin
and end
. Optional argument exclude_end
determines whether object end
is included as the last object in the range:
Range.new(2, 5).to_a # => [2, 3, 4, 5] Range.new(2, 5, true).to_a # => [2, 3, 4] Range.new('a', 'd').to_a # => ["a", "b", "c", "d"] Range.new('a', 'd', true).to_a # => ["a", "b", "c"]
Constructs a new regular expression from pattern
, which can be either a String
or a Regexp
(in which case that regexp’s options are propagated), and new options may not be specified (a change as of Ruby 1.8).
If options
is an Integer
, it should be one or more of the constants Regexp::EXTENDED
, Regexp::IGNORECASE
, and Regexp::MULTILINE
, or-ed together. Otherwise, if options
is not nil
or false
, the regexp will be case insensitive.
r1 = Regexp.new('^a-z+:\\s+\w+') #=> /^a-z+:\s+\w+/ r2 = Regexp.new('cat', true) #=> /cat/i r3 = Regexp.new(r2) #=> /cat/i r4 = Regexp.new('dog', Regexp::EXTENDED | Regexp::IGNORECASE) #=> /dog/ix
Creates a new set containing the elements of the given enumerable object.
If a block is given, the elements of enum are preprocessed by the given block.
Set.new([1, 2]) #=> #<Set: {1, 2}> Set.new([1, 2, 1]) #=> #<Set: {1, 2}> Set.new([1, 'c', :s]) #=> #<Set: {1, "c", :s}> Set.new(1..5) #=> #<Set: {1, 2, 3, 4, 5}> Set.new([1, 2, 3]) { |x| x * x } #=> #<Set: {1, 4, 9}>
Calls allocate
to create a new object of class’s class, then invokes that object’s initialize method, passing it args. This is the method that ends up getting called whenever an object is constructed using .new
.
Creates a new anonymous (unnamed) class with the given superclass (or Object
if no parameter is given). You can give a class a name by assigning the class object to a constant.
If a block is given, it is passed the class object, and the block is evaluated in the context of this class like class_eval
.
fred = Class.new do def meth1 "hello" end def meth2 "bye" end end a = fred.new #=> #<#<Class:0x100381890>:0x100376b98> a.meth1 #=> "hello" a.meth2 #=> "bye"
Assign the class to a constant (name starting uppercase) if you want to treat it like a regular class.