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 is 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
is given but no block is 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 is given but no default_value
, 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"
If both a block and a default_value
are given, raises an ArgumentError
If the optional keyword argument capacity
is given, the hash will be allocated with enough capacity to accommodate this many keys without having to be resized.
Pass in the obj to delegate method calls to. All methods supported by obj will be delegated to.
Constructs a new ERB
object with the template specified in str.
An ERB
object works by building a chunk of Ruby code that will output the completed template when run.
If trim_mode is passed a String
containing one or more of the following modifiers, ERB
will adjust its code generation as listed:
% enables Ruby code processing for lines beginning with % <> omit newline for lines starting with <% and ending in %> > omit newline for lines ending in %> - omit blank lines ending in -%>
eoutvar can be used to set the name of the variable ERB
will build up its output in. This is useful when you need to run multiple ERB
templates through the same binding and/or when you want to control where output ends up. Pass the name of the variable to be used inside a String
.
require "erb" # build data class class Listings PRODUCT = { :name => "Chicken Fried Steak", :desc => "A well messages pattie, breaded and fried.", :cost => 9.95 } attr_reader :product, :price def initialize( product = "", price = "" ) @product = product @price = price end def build b = binding # create and run templates, filling member data variables ERB.new(<<~'END_PRODUCT', trim_mode: "", eoutvar: "@product").result b <%= PRODUCT[:name] %> <%= PRODUCT[:desc] %> END_PRODUCT ERB.new(<<~'END_PRICE', trim_mode: "", eoutvar: "@price").result b <%= PRODUCT[:name] %> -- <%= PRODUCT[:cost] %> <%= PRODUCT[:desc] %> END_PRICE end end # setup template data listings = Listings.new listings.build puts listings.product + "\n" + listings.price
Generates
Chicken Fried Steak A well messages pattie, breaded and fried. Chicken Fried Steak -- 9.95 A well messages pattie, breaded and fried.
Creates a new ipaddr object either from a human readable IP address representation in string, or from a packed in_addr
value followed by an address family.
In the former case, the following are the valid formats that will be recognized: “address”, “address/prefixlen” and “address/mask”, where IPv6 address may be enclosed in square brackets (‘[’ and ‘]’). If a prefixlen or a mask is specified, it returns a masked IP address. Although the address family is determined automatically from a specified string, you can specify one explicitly by the optional second argument.
Otherwise an IP address is generated from a packed in_addr
value and an address family.
The IPAddr
class defines many methods and operators, and some of those, such as &, |, include? and ==, accept a string, or a packed in_addr
value instead of an IPAddr
object.
Creates a new XMP
object.
The top-level binding or, optional bind
parameter will be used when creating the workspace. See WorkSpace.new for more information.
This uses the :XMP
prompt mode. See Custom Prompts for more information.
With the single argument logdev
, returns a new logger with all default options:
Logger.new('t.log') # => #<Logger:0x000001e685dc6ac8>
Argument logdev
must be one of:
A string filepath: entries are to be written to the file at that path; if the file at that path exists, new entries are appended.
An IO
stream (typically +$stdout+, +$stderr+. or an open file): entries are to be written to the given stream.
nil
or File::NULL
: no entries are to be written.
Examples:
Logger.new('t.log') Logger.new($stdout)
The keyword options are:
level
: sets the log level; default value is Logger::DEBUG. See Log Level:
Logger.new('t.log', level: Logger::ERROR)
progname
: sets the default program name; default is nil
. See Program Name:
Logger.new('t.log', progname: 'mung')
formatter
: sets the entry formatter; default is nil
. See formatter=.
datetime_format
: sets the format for entry timestamp; default is nil
. See datetime_format=
.
binmode
: sets whether the logger writes in binary mode; default is false
.
shift_period_suffix
: sets the format for the filename suffix for periodic log file rotation; default is '%Y%m%d'
. See Periodic Rotation.
reraise_write_errors
: An array of exception classes, which will be reraised if there is an error when writing to the log device. The default is to swallow all exceptions raised.
Initializes the instance and yields itself if called with a block.
banner
Banner message.
width
Summary width.
indent
Summary indent.
Pushes a new List
.
If a block is given, yields self
and returns the result of the block, otherwise returns self
.
Constructors for classes defined with ::define
accept both positional and keyword arguments.
Measure = Data.define(:amount, :unit) Measure.new(1, 'km') #=> #<data Measure amount=1, unit="km"> Measure.new(amount: 1, unit: 'km') #=> #<data Measure amount=1, unit="km"> # Alternative shorter initialization with [] Measure[1, 'km'] #=> #<data Measure amount=1, unit="km"> Measure[amount: 1, unit: 'km'] #=> #<data Measure amount=1, unit="km">
All arguments are mandatory (unlike Struct
), and converted to keyword arguments:
Measure.new(amount: 1) # in `initialize': missing keyword: :unit (ArgumentError) Measure.new(1) # in `initialize': missing keyword: :unit (ArgumentError)
Note that Measure#initialize
always receives keyword arguments, and that mandatory arguments are checked in initialize
, not in new
. This can be important for redefining initialize in order to convert arguments or provide defaults:
Measure = Data.define(:amount, :unit) do NONE = Data.define def initialize(amount:, unit: NONE.new) super(amount: Float(amount), unit:) end end Measure.new('10', 'km') # => #<data Measure amount=10.0, unit="km"> Measure.new(10_000) # => #<data Measure amount=10000.0, unit=#<data NONE>>
Creates a buffer for pretty printing.
output
is an output target. If it is not specified, ” is assumed. It should have a << method which accepts the first argument obj
of PrettyPrint#text
, the first argument sep
of PrettyPrint#breakable
, the first argument newline
of PrettyPrint.new
, and the result of a given block for PrettyPrint.new
.
maxwidth
specifies maximum line length. If it is not specified, 79 is assumed. However actual outputs may overflow maxwidth
if long non-breakable texts are provided.
newline
is used for line breaks. “n” is used if it is not specified.
The block is used to generate spaces. {|width| ‘ ’ * width} is used if it is not given.
Returns a new PStore object.
Argument file
is the path to the file in which objects are to be stored; if the file exists, it should be one that was written by PStore.
path = 't.store' store = PStore.new(path)
A PStore object is reentrant. If argument thread_safe
is given as true
, the object is also thread-safe (at the cost of a small performance penalty):
store = PStore.new(path, true)
Creates a new Resolv
using resolvers
.
If resolvers
is not given, a hash, or nil
, uses a Hosts
resolver and and a DNS
resolver. If resolvers
is a hash, uses the hash as configuration for the DNS
resolver.
Creates a file in the underlying file system; returns a new Tempfile object based on that file.
If possible, consider instead using Tempfile.create
, which:
Avoids the performance cost of delegation, incurred when Tempfile.new
calls its superclass DelegateClass(File)
.
Does not rely on a finalizer to close and unlink the file, which can be unreliable.
Creates and returns file whose:
Class
is Tempfile (not File, as in Tempfile.create
).
Directory is the system temporary directory (system-dependent).
Generated filename is unique in that directory.
Permissions are 0600
; see File Permissions.
Mode is 'w+'
(read/write mode, positioned at the end).
The underlying file is removed when the Tempfile object dies and is reclaimed by the garbage collector.
Example:
f = Tempfile.new # => #<Tempfile:/tmp/20220505-17839-1s0kt30> f.class # => Tempfile f.path # => "/tmp/20220505-17839-1s0kt30" f.stat.mode.to_s(8) # => "100600" File.exist?(f.path) # => true File.unlink(f.path) # File.exist?(f.path) # => false
Argument basename
, if given, may be one of:
A string: the generated filename begins with basename
:
Tempfile.new('foo') # => #<Tempfile:/tmp/foo20220505-17839-1whk2f>
An array of two strings [prefix, suffix]
: the generated filename begins with prefix
and ends with suffix
:
Tempfile.new(%w/foo .jpg/) # => #<Tempfile:/tmp/foo20220505-17839-58xtfi.jpg>
With arguments basename
and tmpdir
, the file is created in directory tmpdir
:
Tempfile.new('foo', '.') # => #<Tempfile:./foo20220505-17839-xfstr8>
Keyword arguments mode
and options
are passed directly to method File.open
:
The value given with mode
must be an integer, and may be expressed as the logical OR of constants defined in File::Constants
.
For options
, see Open Options.
Related: Tempfile.create
.
Creates a weak reference to orig
Creates a new Proc
object, bound to the current context.
proc = Proc.new { "hello" } proc.call #=> "hello"
Raises ArgumentError
if called without a block.
Proc.new #=> ArgumentError
Create a new Ractor with args and a block.
The given block (Proc
) will be isolated (can’t access any outer variables). self
inside the block will refer to the current Ractor.
r = Ractor.new { puts "Hi, I am #{self.inspect}" } r.take # Prints "Hi, I am #<Ractor:#2 test.rb:1 running>"
Any args
passed are propagated to the block arguments by the same rules as objects sent via send
/Ractor.receive. If an argument in args
is not shareable, it will be copied (via deep cloning, which might be inefficient).
arg = [1, 2, 3] puts "Passing: #{arg} (##{arg.object_id})" r = Ractor.new(arg) {|received_arg| puts "Received: #{received_arg} (##{received_arg.object_id})" } r.take # Prints: # Passing: [1, 2, 3] (#280) # Received: [1, 2, 3] (#300)
Ractor’s name
can be set for debugging purposes:
r = Ractor.new(name: 'my ractor') {}; r.take p r #=> #<Ractor:#3 my ractor test.rb:1 terminated>
Creates a new PRNG using seed
to set the initial state. If seed
is omitted, the generator is initialized with Random.new_seed
.
See Random.srand
for more information on the use of seed values.
Creates a new thread executing the given block.
Any args
given to ::new
will be passed to the block:
arr = [] a, b, c = 1, 2, 3 Thread.new(a,b,c) { |d,e,f| arr << d << e << f }.join arr #=> [1, 2, 3]
A ThreadError
exception is raised if ::new
is called without a block.
If you’re going to subclass Thread
, be sure to call super in your initialize
method, otherwise a ThreadError
will be raised.
Returns a new TracePoint
object, not enabled by default.
To activate the TracePoint
object, use TracePoint#enable
:
trace = TracePoint.new(:call) do |tp| p [tp.lineno, tp.defined_class, tp.method_id, tp.event] end #=> #<TracePoint:disabled> trace.enable #=> false puts "Hello, TracePoint!" # ... # [48, IRB::Notifier::AbstractNotifier, :printf, :call] # ...
To deactivate the trace, use TracePoint#disable
.
trace.disable
See Events at TracePoint
for possible events and more information.
A block must be given; otherwise, an ArgumentError
is raised.
If the trace method isn’t included in the given events filter, a RuntimeError
is raised.
TracePoint.trace(:line) do |tp| p tp.raised_exception end #=> RuntimeError: 'raised_exception' not supported by this event
If the trace method is called outside a block, a RuntimeError
is raised.
TracePoint.trace(:line) do |tp| $tp = tp end $tp.lineno #=> access from outside (RuntimeError)
Access from other threads is also forbidden.
Document-class: UncaughtThrowError
Raised when throw
is called with a tag which does not have corresponding catch
block.
throw "foo", "bar"
raises the exception:
UncaughtThrowError: uncaught throw "foo"
Use extend MonitorMixin
or include MonitorMixin
instead of this constructor. Have look at the examples above to understand how to use this module.