Activates the trace.
Returns true
if trace was enabled. Returns false
if trace was disabled.
trace.enabled? #=> false trace.enable #=> false (previous state) # trace is enabled trace.enabled? #=> true trace.enable #=> true (previous state) # trace is still enabled
If a block is given, the trace will only be enabled during the block call. If target and target_line are both nil, then target_thread will default to the current thread if a block is given.
trace.enabled? #=> false trace.enable do trace.enabled? # only enabled for this block and thread end trace.enabled? #=> false
target
, target_line
and target_thread
parameters are used to limit tracing only to specified code objects. target
should be a code object for which RubyVM::InstructionSequence.of
will return an instruction sequence.
t = TracePoint.new(:line) { |tp| p tp } def m1 p 1 end def m2 p 2 end t.enable(target: method(:m1)) m1 # prints #<TracePoint:line test.rb:4 in `m1'> m2 # prints nothing
Note: You cannot access event hooks within the enable
block.
trace.enable { p tp.lineno } #=> RuntimeError: access from outside
Deactivates the trace
Return true if trace was enabled. Return false if trace was disabled.
trace.enabled? #=> true trace.disable #=> true (previous status) trace.enabled? #=> false trace.disable #=> false
If a block is given, the trace will only be disable within the scope of the block.
trace.enabled? #=> true trace.disable do trace.enabled? # only disabled for this block end trace.enabled? #=> true
Note: You cannot access event hooks within the block.
trace.disable { p tp.lineno } #=> RuntimeError: access from outside
The current status of the trace
Returns a new Complex object if the arguments are valid; otherwise raises an exception if exception
is true
; otherwise returns nil
.
With Numeric
arguments real
and imag
, returns Complex.rect(real, imag)
if the arguments are valid.
With string argument s
, returns a new Complex object if the argument is valid; the string may have:
One or two numeric substrings, each of which specifies a Complex
, Float
, Integer
, Numeric
, or Rational
value, specifying rectangular coordinates:
Sign-separated real and imaginary numeric substrings (with trailing character 'i'
):
Complex('1+2i') # => (1+2i) Complex('+1+2i') # => (1+2i) Complex('+1-2i') # => (1-2i) Complex('-1+2i') # => (-1+2i) Complex('-1-2i') # => (-1-2i)
Real-only numeric string (without trailing character 'i'
):
Complex('1') # => (1+0i) Complex('+1') # => (1+0i) Complex('-1') # => (-1+0i)
Imaginary-only numeric string (with trailing character 'i'
):
Complex('1i') # => (0+1i) Complex('+1i') # => (0+1i) Complex('-1i') # => (0-1i)
At-sign separated real and imaginary rational substrings, each of which specifies a Rational
value, specifying polar coordinates:
Complex('1/2@3/4') # => (0.36584443443691045+0.34081938001166706i) Complex('+1/2@+3/4') # => (0.36584443443691045+0.34081938001166706i) Complex('+1/2@-3/4') # => (0.36584443443691045-0.34081938001166706i) Complex('-1/2@+3/4') # => (-0.36584443443691045-0.34081938001166706i) Complex('-1/2@-3/4') # => (-0.36584443443691045+0.34081938001166706i)
Returns the name at the definition of the current method as a Symbol
. If called outside of a method, it returns nil
.
Returns the called name of the current method as a Symbol
. If called outside of a method, it returns nil
.
Suspends execution of the current thread for the number of seconds specified by numeric argument secs
, or forever if secs
is nil
; returns the integer number of seconds suspended (rounded).
Time.new # => 2008-03-08 19:56:19 +0900 sleep 1.2 # => 1 Time.new # => 2008-03-08 19:56:20 +0900 sleep 1.9 # => 2 Time.new # => 2008-03-08 19:56:22 +0900
Returns the current execution stack—an array containing strings in the form file:line
or file:line: in `method'
.
The optional start parameter determines the number of initial stack entries to omit from the top of the stack.
A second optional length
parameter can be used to limit how many entries are returned from the stack.
Returns nil
if start is greater than the size of current execution stack.
Optionally you can pass a range, which will return an array containing the entries within the specified range.
def a(skip) caller(skip) end def b(skip) a(skip) end def c(skip) b(skip) end c(0) #=> ["prog:2:in `a'", "prog:5:in `b'", "prog:8:in `c'", "prog:10:in `<main>'"] c(1) #=> ["prog:5:in `b'", "prog:8:in `c'", "prog:11:in `<main>'"] c(2) #=> ["prog:8:in `c'", "prog:12:in `<main>'"] c(3) #=> ["prog:13:in `<main>'"] c(4) #=> [] c(5) #=> nil
Returns the result of applying a reducer to an initial value and the first element of the Enumerable
. It then takes the result and applies the function to it and the second element of the collection, and so on. The return value is the result returned by the final call to the function.
You can think of
[ a, b, c, d ].inject(i) { |r, v| fn(r, v) }
as being
fn(fn(fn(fn(i, a), b), c), d)
In a way the inject
function injects the function between the elements of the enumerable.
inject
is aliased as reduce
. You use it when you want to reduce a collection to a single value.
The Calling Sequences
Let’s start with the most verbose:
enum.inject(initial_value) do |result, next_value| # do something with +result+ and +next_value+ # the value returned by the block becomes the # value passed in to the next iteration # as +result+ end
For example:
product = [ 2, 3, 4 ].inject(1) do |result, next_value| result * next_value end product #=> 24
When this runs, the block is first called with 1
(the initial value) and 2
(the first element of the array). The block returns 1*2
, so on the next iteration the block is called with 2
(the previous result) and 3
. The block returns 6
, and is called one last time with 6
and 4
. The result of the block, 24
becomes the value returned by inject
. This code returns the product of the elements in the enumerable.
First Shortcut: Default Initial value
In the case of the previous example, the initial value, 1
, wasn’t really necessary: the calculation of the product of a list of numbers is self-contained.
In these circumstances, you can omit the initial_value
parameter. inject
will then initially call the block with the first element of the collection as the result
parameter and the second element as the next_value
.
[ 2, 3, 4 ].inject do |result, next_value| result * next_value end
This shortcut is convenient, but can only be used when the block produces a result which can be passed back to it as a first parameter.
Here’s an example where that’s not the case: it returns a hash where the keys are words and the values are the number of occurrences of that word in the enumerable.
freqs = File.read("README.md") .scan(/\w{2,}/) .reduce(Hash.new(0)) do |counts, word| counts[word] += 1 counts end freqs #=> {"Actions"=>4, "Status"=>5, "MinGW"=>3, "https"=>27, "github"=>10, "com"=>15, ...
Note that the last line of the block is just the word counts
. This ensures the return value of the block is the result that’s being calculated.
Second Shortcut: a Reducer function
A reducer function is a function that takes a partial result and the next value, returning the next partial result. The block that is given to inject
is a reducer.
You can also write a reducer as a function and pass the name of that function (as a symbol) to inject
. However, for this to work, the function
Must be defined on the type of the result value
Must accept a single parameter, the next value in the collection, and
Must return an updated result which will also implement the function.
Here’s an example that adds elements to a string. The two calls invoke the functions String#concat
and String#+
on the result so far, passing it the next value.
s = [ "cat", " ", "dog" ].inject("", :concat) s #=> "cat dog" s = [ "cat", " ", "dog" ].inject("The result is:", :+) s #=> "The result is: cat dog"
Here’s a more complex example when the result object maintains state of a different type to the enumerable elements.
class Turtle def initialize @x = @y = 0 end def move(dir) case dir when "n" then @y += 1 when "s" then @y -= 1 when "e" then @x += 1 when "w" then @x -= 1 end self end end position = "nnneesw".chars.reduce(Turtle.new, :move) position #=>> #<Turtle:0x00000001052f4698 @y=2, @x=1>
Third Shortcut: Reducer With no Initial Value
If your reducer returns a value that it can accept as a parameter, then you don’t have to pass in an initial value. Here :*
is the name of the times function:
product = [ 2, 3, 4 ].inject(:*) product # => 24
String
concatenation again:
s = [ "cat", " ", "dog" ].inject(:+) s #=> "cat dog"
And an example that converts a hash to an array of two-element subarrays.
nested = {foo: 0, bar: 1}.inject([], :push) nested # => [[:foo, 0], [:bar, 1]]
When called with positive integer argument n
and a block, calls the block with each element, then does so again, until it has done so n
times; returns nil
:
a = [] (1..4).cycle(3) {|element| a.push(element) } # => nil a # => [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4] a = [] ('a'..'d').cycle(2) {|element| a.push(element) } a # => ["a", "b", "c", "d", "a", "b", "c", "d"] a = [] {foo: 0, bar: 1, baz: 2}.cycle(2) {|element| a.push(element) } a # => [[:foo, 0], [:bar, 1], [:baz, 2], [:foo, 0], [:bar, 1], [:baz, 2]]
If count is zero or negative, does not call the block.
When called with a block and n
is nil
, cycles forever.
When no block is given, returns an Enumerator
.
Returns a hash that contains filename as key and coverage array as value. If clear
is true, it clears the counters to zero. If stop
is true, it disables coverage measurement.
Dumps obj
as a JSON string, i.e. calls generate on the object and returns the result.
The default options can be changed via method JSON.dump_default_options
.
Argument io
, if given, should respond to method write
; the JSON String is written to io
, and io
is returned. If io
is not given, the JSON String is returned.
Argument limit
, if given, is passed to JSON.generate
as option max_nesting
.
When argument io
is not given, returns the JSON String generated from obj
:
obj = {foo: [0, 1], bar: {baz: 2, bat: 3}, bam: :bad} json = JSON.dump(obj) json # => "{\"foo\":[0,1],\"bar\":{\"baz\":2,\"bat\":3},\"bam\":\"bad\"}"
When argument io
is given, writes the JSON String to io
and returns io
:
path = 't.json' File.open(path, 'w') do |file| JSON.dump(obj, file) end # => #<File:t.json (closed)> puts File.read(path)
Output:
{"foo":[0,1],"bar":{"baz":2,"bat":3},"bam":"bad"}
Dump the contents of a ruby object as JSON
.
output can be one of: :stdout
, :file
, :string
, or IO
object.
:file
means dumping to a tempfile and returning corresponding File
object;
:stdout
means printing the dump and returning nil
;
:string
means returning a string with the dump;
if an instance of IO
object is provided, the output goes there, and the object is returned.
This method is only expected to work with C Ruby. This is an experimental method and is subject to change. In particular, the function signature and output format are not guaranteed to be compatible in future versions of ruby.
Dump Ruby object o
to a YAML
string. Optional options
may be passed in to control the output format. If an IO
object is passed in, the YAML
will be dumped to that IO
object.
Currently supported options are:
:indentation
Number of space characters used to indent. Acceptable value should be in 0..9
range, otherwise option is ignored.
Default: 2
.
:line_width
Max character to wrap line at.
Default: 0
(meaning “wrap at 81”).
:canonical
Write “canonical” YAML
form (very verbose, yet strictly formal).
Default: false
.
:header
Write %YAML [version]
at the beginning of document.
Default: false
.
:stringify_names
Dump symbol keys in Hash
objects as string.
Default: false
.
Example:
# Dump an array, get back a YAML string Psych.dump(['a', 'b']) # => "---\n- a\n- b\n" # Dump an array to an IO object Psych.dump(['a', 'b'], StringIO.new) # => #<StringIO:0x000001009d0890> # Dump an array with indentation set Psych.dump(['a', ['b']], indentation: 3) # => "---\n- a\n- - b\n" # Dump an array to an IO with indentation set Psych.dump(['a', ['b']], StringIO.new, indentation: 3) # Dump hash with symbol keys as string Psych.dump({a: "b"}, stringify_names: true) # => "---\na: b\n"
Calculates Adler-32 checksum for string
, and returns updated value of adler
. If string
is omitted, it returns the Adler-32 initial value. If adler
is omitted, it assumes that the initial value is given to adler
. If string
is an IO
instance, reads from the IO
until the IO
returns nil and returns Adler-32 of all read data.
Example usage:
require "zlib" data = "foo" puts "Adler32 checksum: #{Zlib.adler32(data).to_s(16)}" #=> Adler32 checksum: 2820145
Returns true
if the named file is readable by the effective user and group id of this process. See eaccess(3).
Note that some OS-level security features may cause this to return true even though the file is not readable by the effective user/group.
Returns true
if the named file is writable by the effective user and group id of this process. See eaccess(3).
Note that some OS-level security features may cause this to return true even though the file is not writable by the effective user/group.
Returns true
if the named file is executable by the effective user and group id of this process. See eaccess(3).
Windows does not support execute permissions separately from read permissions. On Windows, a file is only considered executable if it ends in .bat, .cmd, .com, or .exe.
Note that some OS-level security features may cause this to return true even though the file is not executable by the effective user/group.
Returns true
if the named file
exists and is a regular file.
file
can be an IO
object.
If the file
argument is a symbolic link, it will resolve the symbolic link and use the file referenced by the link.
Enables garbage collection, returning true
if garbage collection was previously disabled.
GC.disable #=> false GC.enable #=> true GC.enable #=> false
Disables garbage collection, returning true
if garbage collection was already disabled.
GC.disable #=> false GC.disable #=> true
Returns true
if the file at path new
is newer than all the files at paths in array old_list
; false
otherwise.
Argument new
and the elements of old_list
should be interpretable as paths:
FileUtils.uptodate?('Rakefile', ['Gemfile', 'README.md']) # => true FileUtils.uptodate?('Gemfile', ['Rakefile', 'README.md']) # => false
A non-existent file is considered to be infinitely old.
Related: FileUtils.touch
.
Returns true
if the file at path new
is newer than all the files at paths in array old_list
; false
otherwise.
Argument new
and the elements of old_list
should be interpretable as paths:
FileUtils.uptodate?('Rakefile', ['Gemfile', 'README.md']) # => true FileUtils.uptodate?('Gemfile', ['Rakefile', 'README.md']) # => false
A non-existent file is considered to be infinitely old.
Related: FileUtils.touch
.