Returns a Proc
object corresponding to this method.
Returns the original name of the method.
class C def foo; end alias bar foo end C.instance_method(:bar).original_name # => :foo
Returns the original name of the method.
class C def foo; end alias bar foo end C.instance_method(:bar).original_name # => :foo
Receive only a specific message.
Instead of Ractor.receive
, Ractor.receive_if
can be given a pattern (or any filter) in a block and you can choose the messages to accept that are available in your ractor’s incoming queue.
r = Ractor.new do p Ractor.receive_if{|msg| msg.match?(/foo/)} #=> "foo3" p Ractor.receive_if{|msg| msg.match?(/bar/)} #=> "bar1" p Ractor.receive_if{|msg| msg.match?(/baz/)} #=> "baz2" end r << "bar1" r << "baz2" r << "foo3" r.take
This will output:
foo3 bar1 baz2
If the block returns a truthy value, the message is removed from the incoming queue and returned. Otherwise, the message remains in the incoming queue and the next messages are checked by the given block.
If there are no messages left in the incoming queue, the method will block until new messages arrive.
If the block is escaped by break/return/exception/throw, the message is removed from the incoming queue as if a truthy value had been returned.
r = Ractor.new do val = Ractor.receive_if{|msg| msg.is_a?(Array)} puts "Received successfully: #{val}" end r.send(1) r.send('test') wait puts "2 non-matching sent, nothing received" r.send([1, 2, 3]) wait
Prints:
2 non-matching sent, nothing received Received successfully: [1, 2, 3]
Note that you can not call receive/receive_if in the given block recursively. You should not do any tasks in the block other than message filtration.
Ractor.current << true Ractor.receive_if{|msg| Ractor.receive} #=> `receive': can not call receive/receive_if recursively (Ractor::Error)
same as Ractor.receive_if
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.
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.
Generally, while a TracePoint
callback is running, other registered callbacks are not called to avoid confusion from reentrance. This method allows reentrance within a given block. Use this method carefully to avoid infinite callback invocation.
If called when reentrance is already allowed, it raises a RuntimeError
.
Example:
# Without reentry # --------------- line_handler = TracePoint.new(:line) do |tp| next if tp.path != __FILE__ # Only works in this file puts "Line handler" binding.eval("class C; end") end.enable class_handler = TracePoint.new(:class) do |tp| puts "Class handler" end.enable class B end # This script will print "Class handler" only once: when inside the :line # handler, all other handlers are ignored. # With reentry # ------------ line_handler = TracePoint.new(:line) do |tp| next if tp.path != __FILE__ # Only works in this file next if (__LINE__..__LINE__+3).cover?(tp.lineno) # Prevent infinite calls puts "Line handler" TracePoint.allow_reentry { binding.eval("class C; end") } end.enable class_handler = TracePoint.new(:class) do |tp| puts "Class handler" end.enable class B end # This will print "Class handler" twice: inside the allow_reentry block in the :line # handler, other handlers are enabled.
Note that the example shows the principal effect of the method, but its practical usage is for debugging libraries that sometimes require other libraries’ hooks to not be affected by the debugger being inside trace point handling. Precautions should be taken against infinite recursion in this case (note that we needed to filter out calls by itself from the :line handler, otherwise it would call itself infinitely).
Returns the return value from :return
, :c_return
, and :b_return
events.
Returns the compiled instruction sequence represented by a RubyVM::InstructionSequence
instance on the :script_compiled
event.
Note that this method is CRuby-specific.
Returns a pretty printed object as a string.
See the PP
module for more information.
With a block given, returns an array of elements of self
, sorted according to the value returned by the block for each element. The ordering of equal elements is indeterminate and may be unstable.
Examples:
a = %w[xx xxx x xxxx] a.sort_by {|s| s.size } # => ["x", "xx", "xxx", "xxxx"] a.sort_by {|s| -s.size } # => ["xxxx", "xxx", "xx", "x"] h = {foo: 2, bar: 1, baz: 0} h.sort_by{|key, value| value } # => [[:baz, 0], [:bar, 1], [:foo, 2]] h.sort_by{|key, value| key } # => [[:bar, 1], [:baz, 0], [:foo, 2]]
With no block given, returns an Enumerator
.
The current implementation of sort_by
generates an array of tuples containing the original collection element and the mapped value. This makes sort_by
fairly expensive when the keysets are simple.
require 'benchmark' a = (1..100000).map { rand(100000) } Benchmark.bm(10) do |b| b.report("Sort") { a.sort } b.report("Sort by") { a.sort_by { |a| a } } end
produces:
user system total real Sort 0.180000 0.000000 0.180000 ( 0.175469) Sort by 1.980000 0.040000 2.020000 ( 2.013586)
However, consider the case where comparing the keys is a non-trivial operation. The following code sorts some files on modification time using the basic sort
method.
files = Dir["*"] sorted = files.sort { |a, b| File.new(a).mtime <=> File.new(b).mtime } sorted #=> ["mon", "tues", "wed", "thurs"]
This sort is inefficient: it generates two new File
objects during every comparison. A slightly better technique is to use the Kernel#test
method to generate the modification times directly.
files = Dir["*"] sorted = files.sort { |a, b| test(?M, a) <=> test(?M, b) } sorted #=> ["mon", "tues", "wed", "thurs"]
This still generates many unnecessary Time
objects. A more efficient technique is to cache the sort keys (modification times in this case) before the sort. Perl users often call this approach a Schwartzian transform, after Randal Schwartz. We construct a temporary array, where each element is an array containing our sort key along with the filename. We sort this array, and then extract the filename from the result.
sorted = Dir["*"].collect { |f| [test(?M, f), f] }.sort.collect { |f| f[1] } sorted #=> ["mon", "tues", "wed", "thurs"]
This is exactly what sort_by
does internally.
sorted = Dir["*"].sort_by { |f| test(?M, f) } sorted #=> ["mon", "tues", "wed", "thurs"]
To produce the reverse of a specific order, the following can be used:
ary.sort_by { ... }.reverse!
With a block given, calls the block with each element, but in reverse order; returns self
:
a = [] (1..4).reverse_each {|element| a.push(-element) } # => 1..4 a # => [-4, -3, -2, -1] a = [] %w[a b c d].reverse_each {|element| a.push(element) } # => ["a", "b", "c", "d"] a # => ["d", "c", "b", "a"] a = [] h.reverse_each {|element| a.push(element) } # => {:foo=>0, :bar=>1, :baz=>2} a # => [[:baz, 2], [:bar, 1], [:foo, 0]]
With no block given, returns an Enumerator
.
Makes a set from the enumerable object with given arguments. Needs to require "set"
to use this method.
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], ... }
Sets create identifier, which is used to decide if the json_create hook of a class should be called; initial value is json_class
:
JSON.create_id # => 'json_class'
Returns the current create identifier. See also JSON.create_id=
.
Arguments obj
and opts
here are the same as arguments obj
and opts
in JSON.generate
.
By default, generates JSON data without checking for circular references in obj
(option max_nesting
set to false
, disabled).
Raises an exception if obj
contains circular references:
a = []; b = []; a.push(b); b.push(a) # Raises SystemStackError (stack level too deep): JSON.fast_generate(a)
Arguments obj
and opts
here are the same as arguments obj
and opts
in JSON.generate
.
Default options are:
{ indent: ' ', # Two spaces space: ' ', # One space array_nl: "\n", # Newline object_nl: "\n" # Newline }
Example:
obj = {foo: [:bar, :baz], bat: {bam: 0, bad: 1}} json = JSON.pretty_generate(obj) puts json
Output:
{ "foo": [ "bar", "baz" ], "bat": { "bam": 0, "bad": 1 } }
Turns FIPS mode on or off. Turning on FIPS mode will obviously only have an effect for FIPS-capable installations of the OpenSSL
library. Trying to do so otherwise will result in an error.
OpenSSL.fips_mode = true # turn FIPS mode on OpenSSL.fips_mode = false # and off again
Dump Ruby object
to a JSON
string.
Returns true
if the named file is writable by the real user and group id of this process. See access(3).
Note that some OS-level security features may cause this to return true even though the file is not writable by the real user/group.