Creates and returns a new IO object (file stream) from a file descriptor.
IO.new may be useful for interaction with low-level libraries. For higher-level interactions, it may be simpler to create the file stream using File.open
.
Argument fd
must be a valid file descriptor (integer):
path = 't.tmp' fd = IO.sysopen(path) # => 3 IO.new(fd) # => #<IO:fd 3>
The new IO object does not inherit encoding (because the integer file descriptor does not have an encoding):
fd = IO.sysopen('t.rus', 'rb') io = IO.new(fd) io.external_encoding # => #<Encoding:UTF-8> # Not ASCII-8BIT.
Optional argument mode
(defaults to ‘r’) must specify a valid mode; see Access Modes:
IO.new(fd, 'w') # => #<IO:fd 3> IO.new(fd, File::WRONLY) # => #<IO:fd 3>
Optional keyword arguments opts
specify:
Encoding options.
Examples:
IO.new(fd, internal_encoding: nil) # => #<IO:fd 3> IO.new(fd, autoclose: true) # => #<IO:fd 3>
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"]
With argument string
given, returns a new regexp with the given string and options:
r = Regexp.new('foo') # => /foo/ r.source # => "foo" r.options # => 0
Optional argument options
is one of the following:
A String
of options:
Regexp.new('foo', 'i') # => /foo/i Regexp.new('foo', 'im') # => /foo/im
The bit-wise OR of one or more of the constants Regexp::EXTENDED
, Regexp::IGNORECASE
, Regexp::MULTILINE
, and Regexp::NOENCODING
:
Regexp.new('foo', Regexp::IGNORECASE) # => /foo/i Regexp.new('foo', Regexp::EXTENDED) # => /foo/x Regexp.new('foo', Regexp::MULTILINE) # => /foo/m Regexp.new('foo', Regexp::NOENCODING) # => /foo/n flags = Regexp::IGNORECASE | Regexp::EXTENDED | Regexp::MULTILINE Regexp.new('foo', flags) # => /foo/mix
nil
or false
, which is ignored.
Any other truthy value, in which case the regexp will be case-insensitive.
If optional keyword argument timeout
is given, its float value overrides the timeout interval for the class, Regexp.timeout
. If nil
is passed as +timeout, it uses the timeout interval for the class, Regexp.timeout
.
With argument regexp
given, returns a new regexp. The source, options, timeout are the same as regexp
. options
and n_flag
arguments are ineffective. The timeout can be overridden by timeout
keyword.
options = Regexp::MULTILINE r = Regexp.new('foo', options, timeout: 1.1) # => /foo/m r2 = Regexp.new(r) # => /foo/m r2.timeout # => 1.1 r3 = Regexp.new(r, timeout: 3.14) # => /foo/m r3.timeout # => 3.14
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}>
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, or via keyword arguments
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 # Initialization with keyword arguments: Foo.new(foo: 0) # => #<struct Struct::Foo foo=0, bar=nil> Foo.new(foo: 0, bar: 1) # => #<struct Struct::Foo foo=0, bar=1> Foo.new(foo: 0, bar: 1, baz: 2) # Raises ArgumentError: unknown keywords: baz
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 can be both positional and keyword arguments.
Optional keyword argument keyword_init:
allows to force only one type of arguments to be accepted:
KeywordsOnly = Struct.new(:foo, :bar, keyword_init: true) KeywordsOnly.new(bar: 1, foo: 0) # => #<struct KeywordsOnly foo=0, bar=1> KeywordsOnly.new(0, 1) # Raises ArgumentError: wrong number of arguments PositionalOnly = Struct.new(:foo, :bar, keyword_init: false) PositionalOnly.new(0, 1) # => #<struct PositionalOnly foo=0, bar=1> PositionalOnly.new(bar: 1, foo: 0) # => #<struct PositionalOnly foo={:foo=>1, :bar=>2}, bar=nil> # Note that no error is raised, but arguments treated as one hash value # Same as not providing keyword_init: Any = Struct.new(:foo, :bar, keyword_init: nil) Any.new(foo: 1, bar: 2) # => #<struct Any foo=1, bar=2> Any.new(1, 2) # => #<struct Any foo=1, bar=2>
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.
Create a Pathname
object from the given String
(or String-like object). If path
contains a NULL character (\0
), an ArgumentError
is raised.
Creates a new socket object.
domain should be a communications domain such as: :INET, :INET6, :UNIX, etc.
socktype should be a socket type such as: :STREAM, :DGRAM, :RAW, etc.
protocol is optional and should be a protocol defined in the domain. If protocol is not given, 0 is used internally.
Socket.new(:INET, :STREAM) # TCP socket Socket.new(:INET, :DGRAM) # UDP socket Socket.new(:UNIX, :STREAM) # UNIX stream socket Socket.new(:UNIX, :DGRAM) # UNIX datagram socket
returns a new instance of Addrinfo
. The instance contains sockaddr, family, socktype, protocol. sockaddr means struct sockaddr which can be used for connect(2), etc. family, socktype and protocol are integers which is used for arguments of socket(2).
sockaddr is specified as an array or a string. The array should be compatible to the value of IPSocket#addr
or UNIXSocket#addr
. The string should be struct sockaddr as generated by Socket.sockaddr_in
or Socket.unpack_sockaddr_un
.
sockaddr examples:
["AF_INET", 46102, "localhost.localdomain", "127.0.0.1"]
["AF_INET6", 42304, "ip6-localhost", "::1"]
["AF_UNIX", "/tmp/sock"]
In an AF_INET/AF_INET6 sockaddr array, the 4th element, numeric IP address, is used to construct socket address in the Addrinfo
instance. If the 3rd element, textual host name, is non-nil, it is also recorded but used only for Addrinfo#inspect
.
family is specified as an integer to specify the protocol family such as Socket::PF_INET. It can be a symbol or a string which is the constant name with or without PF_ prefix such as :INET, :INET6, :UNIX, “PF_INET”, etc. If omitted, PF_UNSPEC is assumed.
socktype is specified as an integer to specify the socket type such as Socket::SOCK_STREAM. It can be a symbol or a string which is the constant name with or without SOCK_ prefix such as :STREAM, :DGRAM, :RAW, “SOCK_STREAM”, etc. If omitted, 0 is assumed.
protocol is specified as an integer to specify the protocol such as Socket::IPPROTO_TCP. It must be an integer, unlike family and socktype. If omitted, 0 is assumed. Note that 0 is reasonable value for most protocols, except raw socket.
Creates a new UDPSocket
object.
address_family should be an integer, a string or a symbol: Socket::AF_INET, “AF_INET”, :INET, etc.
require 'socket' UDPSocket.new #=> #<UDPSocket:fd 3> UDPSocket.new(Socket::AF_INET6) #=> #<UDPSocket:fd 4>
Creates a new server socket bound to port.
If hostname is given, the socket is bound to it.
serv = TCPServer.new("127.0.0.1", 28561) s = serv.accept s.puts Time.now s.close
Internally, TCPServer.new
calls getaddrinfo() function to obtain addresses. If getaddrinfo() returns multiple addresses, TCPServer.new
tries to create a server socket for each address and returns first one that is successful.
Creates a new UNIX server socket bound to path.
require 'socket' serv = UNIXServer.new("/tmp/sock") s = serv.accept p s.read
Opens a SOCKS connection to host
via the SOCKS server.
The SOCKS server configuration varies by implementation
When using the Dante libsocks/libsocksd implementation it is configured as SOCKS_SERVER env var.
See: manpages.debian.org/testing/dante-client/socksify.1.en.html for full env variable support.
Opens a TCP connection to remote_host
on remote_port
. If local_host
and local_port
are specified, then those parameters are used on the local end to establish the connection.
specify the timeout in seconds.
Creates a new UNIX client socket connected to path.
require 'socket' s = UNIXSocket.new("/tmp/sock") s.send "hello", 0
Note that mode
defaults to 'r'
if string
is frozen.
Returns a new StringIO instance formed from string
and mode
; see Access Modes:
strio = StringIO.new # => #<StringIO> strio.close
The instance should be closed when no longer needed.
Related: StringIO.open
(accepts block; closes automatically).
Creates a new StringScanner
object to scan over the given string
.
If fixed_anchor
is true
, \A
always matches the beginning of the string. Otherwise, \A
always matches the current position.
dup
argument is obsolete and not used now.
Returns a new WIN32OLE
object(OLE Automation object). The first argument server specifies OLE Automation server. The first argument should be CLSID or PROGID. If second argument host specified, then returns OLE Automation object on host. If :license keyword argument is provided, IClassFactory2::CreateInstanceLic is used to create instance of licensed server.
WIN32OLE.new('Excel.Application') # => Excel OLE Automation WIN32OLE object. WIN32OLE.new('{00024500-0000-0000-C000-000000000046}') # => Excel OLE Automation WIN32OLE object.
Returns a new BasicObject
.
Returns a new empty Hash object.
The initial default value and initial default proc for the new hash depend on which form above was used. See Default Values.
If neither an argument nor a block given, initializes both the default value and the default proc to nil
:
h = Hash.new h.default # => nil h.default_proc # => nil
If argument default_value
given but no block given, initializes the default value to the given default_value
and the default proc to nil
:
h = Hash.new(false) h.default # => false h.default_proc # => nil
If a block given but no argument, stores the block as the default proc and sets the default value to nil
:
h = Hash.new {|hash, key| "Default value for #{key}" } h.default # => nil h.default_proc.class # => Proc h[:nosuch] # => "Default value for nosuch"
Returns the new CSV object created using string
or io
and the specified options
.
Argument string
should be a String object; it will be put into a new StringIO
object positioned at the beginning.
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 options
: See:
For performance reasons, the options cannot be overridden in a CSV object, so those specified here will endure.
In addition to the CSV instance methods, several IO methods are delegated. See Delegated Methods.
Create a CSV object from a String object:
csv = CSV.new('foo,0') csv # => #<CSV io_type:StringIO encoding:UTF-8 lineno:0 col_sep:"," row_sep:"\n" quote_char:"\"">
Create a CSV object from a File object:
File.write('t.csv', 'foo,0') csv = CSV.new(File.open('t.csv')) csv # => #<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 nil
:
# Raises ArgumentError (Cannot parse nil as CSV): CSV.new(nil)
Pass in the obj to delegate method calls to. All methods supported by obj will be delegated to.