Define methodname as instance method of mod from compiled Ruby source.
example:
filename = 'example.rhtml' # 'arg1' and 'arg2' are used in example.rhtml erb = ERB.new(File.read(filename)) erb.def_method(MyClass, 'render(arg1, arg2)', filename) print MyClass.new.render('foo', 123)
Returns the names of the binding’s local variables as symbols.
def foo a = 1 2.times do |n| binding.local_variables #=> [:a, :n] end end
This method is the short version of the following code:
binding.eval("local_variables")
Adjust the log level during the block execution for the current Fiber
only
logger.with_level(:debug) do logger.debug { "Hello" } end
Outputs obj
to out
like PP.pp
but with no indent and newline.
PP.singleline_pp
returns out
.
Returns the length (in characters) of the matched substring corresponding to the given argument.
When non-negative argument n
is given, returns the length of the matched substring for the n
th match:
m = /(.)(.)(\d+)(\d)(\w)?/.match("THX1138.") # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8" 5:nil> m.match_length(0) # => 6 m.match_length(4) # => 1 m.match_length(5) # => nil
When string or symbol argument name
is given, returns the length of the matched substring for the named match:
m = /(?<foo>.)(.)(?<bar>.+)/.match("hoge") # => #<MatchData "hoge" foo:"h" bar:"ge"> m.match_length('foo') # => 1 m.match_length(:bar) # => 2
This is similar to PrettyPrint::format
but the result has no breaks.
maxwidth
, newline
and genspace
are ignored.
The invocation of breakable
in the block doesn’t break a line and is treated as just an invocation of text
.
This is similar to breakable
except the decision to break or not is determined individually.
Two fill_breakable
under a group may cause 4 results: (break,break), (break,non-break), (non-break,break), (non-break,non-break). This is different to breakable
because two breakable
under a group may cause 2 results: (break,break), (non-break,non-break).
The text sep
is inserted if a line is not broken at this point.
If sep
is not specified, “ ” is used.
If width
is not specified, sep.length
is used. You will have to specify this when sep
is a multibyte character, for example.
Returns a Method
of superclass which would be called when super is used or nil if there is no method on superclass.
Returns a Method
of superclass which would be called when super is used or nil if there is no method on superclass.
Make obj
shareable between ractors.
obj
and all the objects it refers to will be frozen, unless they are already shareable.
If copy
keyword is true
, it will copy objects before freezing them, and will not modify obj
or its internal objects.
Note that the specification and implementation of this method are not mature and may be changed in the future.
obj = ['test'] Ractor.shareable?(obj) #=> false Ractor.make_shareable(obj) #=> ["test"] Ractor.shareable?(obj) #=> true obj.frozen? #=> true obj[0].frozen? #=> true # Copy vs non-copy versions: obj1 = ['test'] obj1s = Ractor.make_shareable(obj1) obj1.frozen? #=> true obj1s.object_id == obj1.object_id #=> true obj2 = ['test'] obj2s = Ractor.make_shareable(obj2, copy: true) obj2.frozen? #=> false obj2s.frozen? #=> true obj2s.object_id == obj2.object_id #=> false obj2s[0].object_id == obj2[0].object_id #=> false
See also the “Shareable and unshareable objects” section in the Ractor
class docs.
Changes asynchronous interrupt timing.
interrupt means asynchronous event and corresponding procedure by Thread#raise
, Thread#kill
, signal trap (not supported yet) and main thread termination (if main thread terminates, then all other thread will be killed).
The given hash
has pairs like ExceptionClass => :TimingSymbol
. Where the ExceptionClass is the interrupt handled by the given block. The TimingSymbol can be one of the following symbols:
:immediate
Invoke interrupts immediately.
:on_blocking
Invoke interrupts while BlockingOperation.
:never
Never invoke all interrupts.
BlockingOperation means that the operation will block the calling thread, such as read and write. On CRuby implementation, BlockingOperation is any operation executed without GVL.
Masked asynchronous interrupts are delayed until they are enabled. This method is similar to sigprocmask(3).
Asynchronous interrupts are difficult to use.
If you need to communicate between threads, please consider to use another way such as Queue
.
Or use them with deep understanding about this method.
In this example, we can guard from Thread#raise
exceptions.
Using the :never
TimingSymbol the RuntimeError
exception will always be ignored in the first block of the main thread. In the second ::handle_interrupt
block we can purposefully handle RuntimeError
exceptions.
th = Thread.new do Thread.handle_interrupt(RuntimeError => :never) { begin # You can write resource allocation code safely. Thread.handle_interrupt(RuntimeError => :immediate) { # ... } ensure # You can write resource deallocation code safely. end } end Thread.pass # ... th.raise "stop"
While we are ignoring the RuntimeError
exception, it’s safe to write our resource allocation code. Then, the ensure block is where we can safely deallocate your resources.
Timeout::Error
In the next example, we will guard from the Timeout::Error
exception. This will help prevent from leaking resources when Timeout::Error
exceptions occur during normal ensure clause. For this example we use the help of the standard library Timeout
, from lib/timeout.rb
require 'timeout' Thread.handle_interrupt(Timeout::Error => :never) { timeout(10){ # Timeout::Error doesn't occur here Thread.handle_interrupt(Timeout::Error => :on_blocking) { # possible to be killed by Timeout::Error # while blocking operation } # Timeout::Error doesn't occur here } }
In the first part of the timeout
block, we can rely on Timeout::Error
being ignored. Then in the Timeout::Error => :on_blocking
block, any operation that will block the calling thread is susceptible to a Timeout::Error
exception being raised.
It’s possible to stack multiple levels of ::handle_interrupt
blocks in order to control more than one ExceptionClass and TimingSymbol at a time.
Thread.handle_interrupt(FooError => :never) { Thread.handle_interrupt(BarError => :never) { # FooError and BarError are prohibited. } }
All exceptions inherited from the ExceptionClass parameter will be considered.
Thread.handle_interrupt(Exception => :never) { # all exceptions inherited from Exception are prohibited. }
For handling all interrupts, use Object
and not Exception
as the ExceptionClass, as kill/terminate interrupts are not handled by Exception
.
Returns an array of the names of the thread-local variables (as Symbols).
thr = Thread.new do Thread.current.thread_variable_set(:cat, 'meow') Thread.current.thread_variable_set("dog", 'woof') end thr.join #=> #<Thread:0x401b3f10 dead> thr.thread_variables #=> [:dog, :cat]
Note that these are not fiber local variables. Please see Thread#[]
and Thread#thread_variable_get
for more details.
Returns true
if the given string (or symbol) exists as a thread-local variable.
me = Thread.current me.thread_variable_set(:oliver, "a") me.thread_variable?(:oliver) #=> true me.thread_variable?(:stanley) #=> false
Note that these are not fiber local variables. Please see Thread#[]
and Thread#thread_variable_get
for more details.
Return the name at the definition of the method being called
Return the called name of the method being called
Returns an array of the names of global variables. This includes special regexp global variables such as $~
and $+
, but does not include the numbered regexp global variables ($1
, $2
, etc.).
global_variables.grep /std/ #=> [:$stdin, :$stdout, :$stderr]
Returns the names of the current local variables.
fred = 1 for i in 1..10 # ... end local_variables #=> [:fred, :i]
Calls the block with successive elements as long as the block returns a truthy value; returns an array of all elements up to that point:
(1..4).take_while{|i| i < 3 } # => [1, 2] h = {foo: 0, bar: 1, baz: 2} h.take_while{|element| key, value = *element; value < 2 } # => [[:foo, 0], [:bar, 1]]
With no block given, returns an Enumerator
.
Calls the block with successive elements as long as the block returns a truthy value; returns an array of all elements after that point:
(1..4).drop_while{|i| i < 3 } # => [3, 4] h = {foo: 0, bar: 1, baz: 2} a = h.drop_while{|element| key, value = *element; value < 2 } a # => [[:baz, 2]]
With no block given, returns an Enumerator
.
Returns a hash that contains filename as key and coverage array as value. This is the same as ‘Coverage.result(stop: false, clear: false)`.
{ "file.rb" => [1, 2, nil], ... }
Dump the contents of the ruby heap as JSON
.
output argument is the same as for dump
.
full must be a boolean. If true, all heap slots are dumped including the empty ones (T_NONE
).
since must be a non-negative integer or nil
.
If since is a positive integer, only objects of that generation and newer generations are dumped. The current generation can be accessed using GC::count
. Objects that were allocated without object allocation tracing enabled are ignored. See ::trace_object_allocations
for more information and examples.
If since is omitted or is nil
, all objects are dumped.
shapes must be a boolean or a non-negative integer.
If shapes is a positive integer, only shapes newer than the provided shape id are dumped. The current shape_id can be accessed using RubyVM.stat(:next_shape_id)
.
If shapes is false
, no shapes are dumped.
To only dump objects allocated past a certain point you can combine since and shapes:
ObjectSpace.trace_object_allocations GC.start gc_generation = GC.count shape_generation = RubyVM.stat(:next_shape_id) call_method_to_instrument ObjectSpace.dump_all(since: gc_generation, shapes: shape_generation)
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 the contents of the ruby shape tree as JSON
.
output argument is the same as for dump
.
If since is a positive integer, only shapes newer than the provided shape id are dumped. The current shape_id can be accessed using RubyVM.stat(:next_shape_id)
.
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.
Parse a file at filename
. Returns the Psych::Nodes::Document
.
Raises a Psych::SyntaxError
when a YAML
syntax error is detected.