Returns true
if yield
would execute a block in the current context. The iterator?
form is mildly deprecated.
def try if block_given? yield else "no block" end end try #=> "no block" try { "hello" } #=> "hello" try do "hello" end #=> "hello"
catch
executes its block. If throw
is not called, the block executes normally, and catch
returns the value of the last expression evaluated.
catch(1) { 123 } # => 123
If throw(tag2, val)
is called, Ruby searches up its stack for a catch
block whose tag
has the same object_id
as tag2. When found, the block stops executing and returns val (or nil
if no second argument was given to throw
).
catch(1) { throw(1, 456) } # => 456 catch(1) { throw(1) } # => nil
When tag
is passed as the first argument, catch
yields it as the parameter of the block.
catch(1) {|x| x + 2 } # => 3
When no tag
is given, catch
yields a new unique object (as from Object.new
) as the block parameter. This object can then be used as the argument to throw
, and will match the correct catch
block.
catch do |obj_A| catch do |obj_B| throw(obj_B, 123) puts "This puts is not reached" end puts "This puts is displayed" 456 end # => 456 catch do |obj_A| catch do |obj_B| throw(obj_A, 123) puts "This puts is still not reached" end puts "Now this puts is also not reached" 456 end # => 123
Transfers control to the end of the active catch
block waiting for tag. Raises UncaughtThrowError
if there is no catch
block for the tag. The optional second parameter supplies a return value for the catch
block, which otherwise defaults to nil
. For examples, see Kernel::catch.
Returns two arrays, the first containing the elements of enum for which the block evaluates to true, the second containing the rest.
If no block is given, an enumerator is returned instead.
(1..6).partition { |v| v.even? } #=> [[2, 4, 6], [1, 3, 5]]
Returns true
if any member of enum equals obj. Equality is tested using ==
.
(1..10).include? 5 #=> true (1..10).include? 15 #=> false (1..10).member? 5 #=> true (1..10).member? 15 #=> false
Computes the arctangent of decimal
to the specified number of digits of precision, numeric
.
If decimal
is NaN, returns NaN.
BigMath.atan(BigDecimal('-1'), 16).to_s #=> "-0.785398163397448309615660845819878471907514682065e0"
Provides a convenient Ruby iterator which executes a block for each entry in the /etc/passwd file.
The code block is passed an Passwd
struct.
See ::getpwent
above for details.
Example:
require 'etc' Etc.passwd {|u| puts u.name + " = " + u.gecos }
Parse the JSON
document source into a Ruby data structure and return it.
opts can have the following keys:
max_nesting: The maximum depth of nesting allowed in the parsed data structures. Disable depth checking with :max_nesting => false. It defaults to 100.
allow_nan: If set to true, allow NaN
, Infinity
and -Infinity in defiance of RFC 7159 to be parsed by the Parser. This option defaults to false.
symbolize_names: If set to true, returns symbols for the names (keys) in a JSON
object. Otherwise strings are returned. Strings are the default.
create_additions: If set to false, the Parser doesn’t create additions even if a matching class and create_id
was found. This option defaults to false.
object_class: Defaults to Hash
array_class: Defaults to Array
Parse the JSON
document source into a Ruby data structure and return it. The bang version of the parse method defaults to the more dangerous values for the opts hash, so be sure only to parse trusted source documents.
opts can have the following keys:
max_nesting: The maximum depth of nesting allowed in the parsed data structures. Enable depth checking with :max_nesting => anInteger. The parse! methods defaults to not doing max depth checking: This can be dangerous if someone wants to fill up your stack.
allow_nan: If set to true, allow NaN
, Infinity
, and -Infinity in defiance of RFC 7159 to be parsed by the Parser. This option defaults to true.
create_additions: If set to false, the Parser doesn’t create additions even if a matching class and create_id
was found. This option defaults to false.
Generate a JSON
document from the Ruby data structure obj and return it. state is * a JSON::State object,
or a Hash
like object (responding to to_hash),
an object convertible into a hash by a to_h method,
that is used as or to configure a State object.
It defaults to a state object, that creates the shortest possible JSON
text in one line, checks for circular data structures and doesn’t allow NaN
, Infinity
, and -Infinity.
A state hash can have the following keys:
indent: a string used to indent levels (default: ”),
space: a string that is put after, a : or , delimiter (default: ”),
space_before: a string that is put before a : pair delimiter (default: ”),
object_nl: a string that is put at the end of a JSON
object (default: ”),
array_nl: a string that is put at the end of a JSON
array (default: ”),
allow_nan: true if NaN
, Infinity
, and -Infinity should be generated, otherwise an exception is thrown if these values are encountered. This options defaults to false.
max_nesting: The maximum depth of nesting allowed in the data structures from which JSON
is to be generated. Disable depth checking with :max_nesting => false, it defaults to 100.
See also the fast_generate
for the fastest creation method with the least amount of sanity checks, and the pretty_generate
method for some defaults for pretty output.
Parse a YAML string in yaml
. Returns the Psych::Nodes::Document
. filename
is used in the exception message if a Psych::SyntaxError
is raised.
Raises a Psych::SyntaxError
when a YAML syntax error is detected.
Example:
Psych.parse("---\n - a\n - b") # => #<Psych::Nodes::Document:0x00> begin Psych.parse("--- `", filename: "file.txt") rescue Psych::SyntaxError => ex ex.file # => 'file.txt' ex.message # => "(file.txt): found character that cannot start any token" end
See Psych::Nodes
for more information about YAML AST.
Returns a default parser
Spawns the specified command on a newly allocated pty. You can also use the alias ::getpty
.
The command’s controlling tty is set to the slave device of the pty and its standard input/output/error is redirected to the slave device.
command
and command_line
are the full commands to run, given a String
. Any additional arguments
will be passed to the command.
In the non-block form this returns an array of size three, [r, w, pid]
.
In the block form these same values will be yielded to the block:
Compresses the given string
. Valid values of level are Zlib::NO_COMPRESSION
, Zlib::BEST_SPEED
, Zlib::BEST_COMPRESSION
, Zlib::DEFAULT_COMPRESSION
, or an integer from 0 to 9.
This method is almost equivalent to the following code:
def deflate(string, level) z = Zlib::Deflate.new(level) dst = z.deflate(string, Zlib::FINISH) z.close dst end
See also Zlib.inflate
Decompresses string
. Raises a Zlib::NeedDict
exception if a preset dictionary is needed for decompression.
This method is almost equivalent to the following code:
def inflate(string) zstream = Zlib::Inflate.new buf = zstream.inflate(string) zstream.finish zstream.close buf end
See also Zlib.deflate
Enables garbage collection, returning true
if garbage collection was previously disabled.
GC.disable #=> false GC.enable #=> true GC.enable #=> false
Returns a Hash
containing information about the GC
.
The hash includes information about internal statistics about GC
such as:
{ :count=>0, :heap_allocated_pages=>24, :heap_sorted_length=>24, :heap_allocatable_pages=>0, :heap_available_slots=>9783, :heap_live_slots=>7713, :heap_free_slots=>2070, :heap_final_slots=>0, :heap_marked_slots=>0, :heap_eden_pages=>24, :heap_tomb_pages=>0, :total_allocated_pages=>24, :total_freed_pages=>0, :total_allocated_objects=>7796, :total_freed_objects=>83, :malloc_increase_bytes=>2389312, :malloc_increase_bytes_limit=>16777216, :minor_gc_count=>0, :major_gc_count=>0, :remembered_wb_unprotected_objects=>0, :remembered_wb_unprotected_objects_limit=>0, :old_objects=>0, :old_objects_limit=>0, :oldmalloc_increase_bytes=>2389760, :oldmalloc_increase_bytes_limit=>16777216 }
The contents of the hash are implementation specific and may be changed in the future.
This method is only expected to work on C Ruby.
Returns the time used to execute the given block as a Benchmark::Tms
object. Takes label
option.
require 'benchmark' n = 1000000 time = Benchmark.measure do n.times { a = "1" } end puts time
Generates:
0.220000 0.000000 0.220000 ( 0.227313)
Returns the elapsed real time used to execute the given block.
Returns the time used to execute the given block as a Benchmark::Tms
object. Takes label
option.
require 'benchmark' n = 1000000 time = Benchmark.measure do n.times { a = "1" } end puts time
Generates:
0.220000 0.000000 0.220000 ( 0.227313)
Returns the elapsed real time used to execute the given block.
The standard configuration object for gems.
Use the given configuration object (which implements the ConfigFile
protocol) as the standard configuration object.
The path to the data directory specified by the gem name. If the package is not available as a gem, return nil.