Creates an option from the given parameters params
. See Parameters for New Options.
The block, if given, is the handler for the created option. When the option is encountered during command-line parsing, the block is called with the argument given for the option, if any. See Option Handlers.
The new option is added at the tail of the summary.
Returns a hash of the name/value pairs, to use in pattern matching.
Measure = Data.define(:amount, :unit) distance = Measure[10, 'km'] distance.deconstruct_keys(nil) #=> {:amount=>10, :unit=>"km"} distance.deconstruct_keys([:amount]) #=> {:amount=>10} # usage case distance in amount:, unit: 'km' # calls #deconstruct_keys underneath puts "It is #{amount} kilometers away" else puts "Don't know how to handle it" end # prints "It is 10 kilometers away"
Or, with checking the class, too:
case distance in Measure(amount:, unit: 'km') puts "It is #{amount} kilometers away" # ... end
Returns a hash of the named captures for the given names.
m = /(?<hours>\d{2}):(?<minutes>\d{2}):(?<seconds>\d{2})/.match("18:37:22") m.deconstruct_keys([:hours, :minutes]) # => {:hours => "18", :minutes => "37"} m.deconstruct_keys(nil) # => {:hours => "18", :minutes => "37", :seconds => "22"}
Returns an empty hash if no named captures were defined:
m = /(\d{2}):(\d{2}):(\d{2})/.match("18:37:22") m.deconstruct_keys(nil) # => {}
Returns the exit value associated with this LocalJumpError
.
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.
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]
Controls tracing of assignments to global variables. The parameter symbol
identifies the variable (as either a string name or a symbol identifier). cmd (which may be a string or a Proc
object) or block is executed whenever the variable is assigned. The block or Proc
object receives the variable’s new value as a parameter. Also see Kernel::untrace_var.
trace_var :$_, proc {|v| puts "$_ is now '#{v}'" } $_ = "hello" $_ = ' there'
produces:
$_ is now 'hello' $_ is now ' there'
Removes tracing for the specified command on the given global variable and returns nil
. If no command is specified, removes all tracing for that variable and returns an array containing the commands actually removed.
Converts block to a Proc
object (and therefore binds it at the point of call) and registers it for execution when the program exits. If multiple handlers are registered, they are executed in reverse order of registration.
def do_at_exit(str1) at_exit { print str1 } end at_exit { puts "cruel world" } do_at_exit("goodbye ") exit
produces:
goodbye cruel world
Returns the names of the current local variables.
fred = 1 for i in 1..10 # ... end local_variables #=> [:fred, :i]
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!
Returns an array of flattened objects returned by the block.
With a block given, calls the block with successive elements; returns a flattened array of objects returned by the block:
[0, 1, 2, 3].flat_map {|element| -element } # => [0, -1, -2, -3] [0, 1, 2, 3].flat_map {|element| [element, -element] } # => [0, 0, 1, -1, 2, -2, 3, -3] [[0, 1], [2, 3]].flat_map {|e| e + [100] } # => [0, 1, 100, 2, 3, 100] {foo: 0, bar: 1, baz: 2}.flat_map {|key, value| [key, value] } # => [:foo, 0, :bar, 1, :baz, 2]
With no block given, returns an Enumerator
.
Alias: collect_concat
.
Calls the block with each successive overlapped n
-tuple of elements; returns self
:
a = [] (1..5).each_cons(3) {|element| a.push(element) } a # => [[1, 2, 3], [2, 3, 4], [3, 4, 5]] a = [] h = {foo: 0, bar: 1, baz: 2, bam: 3} h.each_cons(2) {|element| a.push(element) } a # => [[[:foo, 0], [:bar, 1]], [[:bar, 1], [:baz, 2]], [[:baz, 2], [:bam, 3]]]
With no block given, returns an Enumerator
.
Enters exclusive section.
Returns true if this monitor is locked by any thread
Returns true if this monitor is locked by current thread.
Creates a new MonitorMixin::ConditionVariable
associated with the Monitor
object.
Alias of GC.start
Alias of GC.start
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.