Returns a clone of this method.
class A def foo return "bar" end end m = A.new.method(:foo) m.call # => "bar" n = m.clone.call # => "bar"
Returns a human-readable description of the underlying method.
"cat".method(:count).inspect #=> "#<Method: String#count(*)>" (1..3).method(:map).inspect #=> "#<Method: Range(Enumerable)#map()>"
In the latter case, the method description includes the “owner” of the original method (Enumerable
module, which is included into Range
).
inspect
also provides, when possible, method argument names (call sequence) and source location.
require 'net/http' Net::HTTP.method(:get).inspect #=> "#<Method: Net::HTTP.get(uri_or_host, path=..., port=...) <skip>/lib/ruby/2.7.0/net/http.rb:457>"
...
in argument definition means argument is optional (has some default value).
For methods defined in C (language core and extensions), location and argument names can’t be extracted, and only generic information is provided in form of *
(any number of arguments) or _
(some positional argument).
"cat".method(:count).inspect #=> "#<Method: String#count(*)>" "cat".method(:+).inspect #=> "#<Method: String#+(_)>""
Returns the number of Ractors currently running or blocking (waiting).
Ractor.count #=> 1 r = Ractor.new(name: 'example') { Ractor.yield(1) } Ractor.count #=> 2 (main + example ractor) r.take # wait for Ractor.yield(1) r.take # wait until r will finish Ractor.count #=> 1
Prevents threads from being added to or removed from the receiving ThreadGroup
.
New threads can still be started in an enclosed ThreadGroup
.
ThreadGroup::Default.enclose #=> #<ThreadGroup:0x4029d914> thr = Thread.new { Thread.stop } #=> #<Thread:0x402a7210 sleep> tg = ThreadGroup.new #=> #<ThreadGroup:0x402752d4> tg.add thr #=> ThreadError: can't move from the enclosed thread group
Returns true
if the thgrp
is enclosed. See also ThreadGroup#enclose
.
Wakes up thr
, making it eligible for scheduling.
a = Thread.new { puts "a"; Thread.stop; puts "c" } sleep 0.1 while a.status!='sleep' puts "Got here" a.run a.join
This will produce:
a Got here c
See also the instance method wakeup
.
Returns the priority of thr. Default is inherited from the current thread which creating the new thread, or zero for the initial main thread; higher-priority thread will run more frequently than lower-priority threads (but lower-priority threads can also run).
This is just hint for Ruby thread scheduler. It may be ignored on some platform.
Thread.current.priority #=> 0
Sets the priority of thr to integer. Higher-priority threads will run more frequently than lower-priority threads (but lower-priority threads can also run).
This is just hint for Ruby thread scheduler. It may be ignored on some platform.
count1 = count2 = 0 a = Thread.new do loop { count1 += 1 } end a.priority = -1 b = Thread.new do loop { count2 += 1 } end b.priority = -2 sleep 1 #=> 1 count1 #=> 622504 count2 #=> 5832
Dump the name, id, and status of thr to a string.
Return a string containing a human-readable TracePoint
status.
If object is string-like, parse the string and return the parsed result as a Ruby data structure. Otherwise, generate a JSON
text from the Ruby data structure object and return it.
The opts argument is passed through to generate/parse respectively. See generate and parse for their documentation.
Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. clone
copies the frozen value state of obj, unless the :freeze
keyword argument is given with a false or true value. See also the discussion under Object#dup
.
class Klass attr_accessor :str end s1 = Klass.new #=> #<Klass:0x401b3a38> s1.str = "Hello" #=> "Hello" s2 = s1.clone #=> #<Klass:0x401b3998 @str="Hello"> s2.str[1,4] = "i" #=> "i" s1.inspect #=> "#<Klass:0x401b3a38 @str=\"Hi\">" s2.inspect #=> "#<Klass:0x401b3998 @str=\"Hi\">"
This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy
method of the class.
Returns the count of elements, based on an argument or block criterion, if given.
With no argument and no block given, returns the number of elements:
[0, 1, 2].count # => 3 {foo: 0, bar: 1, baz: 2}.count # => 3
With argument object
given, returns the number of elements that are ==
to object
:
[0, 1, 2, 1].count(1) # => 2
With a block given, calls the block with each element and returns the number of elements for which the block returns a truthy value:
[0, 1, 2, 3].count {|element| element < 2} # => 2 {foo: 0, bar: 1, baz: 2}.count {|key, value| value < 2} # => 2
Returns the first element for which the block returns a truthy value.
With a block given, calls the block with successive elements of the collection; returns the first element for which the block returns a truthy value:
(0..9).find {|element| element > 2} # => 3
If no such element is found, calls if_none_proc
and returns its return value.
(0..9).find(proc {false}) {|element| element > 12} # => false {foo: 0, bar: 1, baz: 2}.find {|key, value| key.start_with?('b') } # => [:bar, 1] {foo: 0, bar: 1, baz: 2}.find(proc {[]}) {|key, value| key.start_with?('c') } # => []
With no block given, returns an Enumerator
.
Returns an array of objects rejected by the block.
With a block given, calls the block with successive elements; returns an array of those elements for which the block returns nil
or false
:
(0..9).reject {|i| i * 2 if i.even? } # => [1, 3, 5, 7, 9] {foo: 0, bar: 1, baz: 2}.reject {|key, value| key if value.odd? } # => {:foo=>0, :baz=>2}
When no block given, returns an Enumerator
.
Related: select
.
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]]
Returns whether exactly one element meets a given criterion.
With no argument and no block, returns whether exactly one element is truthy:
(1..1).one? # => true [1, nil, false].one? # => true (1..4).one? # => false {foo: 0}.one? # => true {foo: 0, bar: 1}.one? # => false [].one? # => false
With argument pattern
and no block, returns whether for exactly one element element
, pattern === element
:
[nil, false, 0].one?(Integer) # => true [nil, false, 0].one?(Numeric) # => true [nil, false, 0].one?(Float) # => false %w[bar baz bat bam].one?(/m/) # => true %w[bar baz bat bam].one?(/foo/) # => false %w[bar baz bat bam].one?('ba') # => false {foo: 0, bar: 1, baz: 2}.one?(Array) # => false {foo: 0}.one?(Array) # => true [].one?(Integer) # => false
With a block given, returns whether the block returns a truthy value for exactly one element:
(1..4).one? {|element| element < 2 } # => true (1..4).one? {|element| element < 1 } # => false {foo: 0, bar: 1, baz: 2}.one? {|key, value| value < 1 } # => true {foo: 0, bar: 1, baz: 2}.one? {|key, value| value < 2 } # => false
Returns whether no element meets a given criterion.
With no argument and no block, returns whether no element is truthy:
(1..4).none? # => false [nil, false].none? # => true {foo: 0}.none? # => false {foo: 0, bar: 1}.none? # => false [].none? # => true
With argument pattern
and no block, returns whether for no element element
, pattern === element
:
[nil, false, 1.1].none?(Integer) # => true %w[bar baz bat bam].none?(/m/) # => false %w[bar baz bat bam].none?(/foo/) # => true %w[bar baz bat bam].none?('ba') # => true {foo: 0, bar: 1, baz: 2}.none?(Hash) # => true {foo: 0}.none?(Array) # => false [].none?(Integer) # => true
With a block given, returns whether the block returns a truthy value for no element:
(1..4).none? {|element| element < 1 } # => true (1..4).none? {|element| element < 2 } # => false {foo: 0, bar: 1, baz: 2}.none? {|key, value| value < 0 } # => true {foo: 0, bar: 1, baz: 2}.none? {|key, value| value < 1 } # => false
Returns whether for any element object == element
:
(1..4).include?(2) # => true (1..4).include?(5) # => false (1..4).include?('2') # => false %w[a b c d].include?('b') # => true %w[a b c d].include?('2') # => false {foo: 0, bar: 1, baz: 2}.include?(:foo) # => true {foo: 0, bar: 1, baz: 2}.include?('foo') # => false {foo: 0, bar: 1, baz: 2}.include?(0) # => false
Each element in the returned enumerator is a 2-element array consisting of:
A value returned by the block.
An array (“chunk”) containing the element for which that value was returned, and all following elements for which the block returned the same value:
So that:
Each block return value that is different from its predecessor begins a new chunk.
Each block return value that is the same as its predecessor continues the same chunk.
Example:
e = (0..10).chunk {|i| (i / 3).floor } # => #<Enumerator: ...> # The enumerator elements. e.next # => [0, [0, 1, 2]] e.next # => [1, [3, 4, 5]] e.next # => [2, [6, 7, 8]] e.next # => [3, [9, 10]]
Method chunk
is especially useful for an enumerable that is already sorted. This example counts words for each initial letter in a large array of words:
# Get sorted words from a web page. url = 'https://raw.githubusercontent.com/eneko/data-repository/master/data/words.txt' words = URI::open(url).readlines # Make chunks, one for each letter. e = words.chunk {|word| word.upcase[0] } # => #<Enumerator: ...> # Display 'A' through 'F'. e.each {|c, words| p [c, words.length]; break if c == 'F' }
Output:
["A", 17096] ["B", 11070] ["C", 19901] ["D", 10896] ["E", 8736] ["F", 6860]
You can use the special symbol :_alone
to force an element into its own separate chuck:
a = [0, 0, 1, 1] e = a.chunk{|i| i.even? ? :_alone : true } e.to_a # => [[:_alone, [0]], [:_alone, [0]], [true, [1, 1]]]
For example, you can put each line that contains a URL into its own chunk:
pattern = /http/ open(filename) { |f| f.chunk { |line| line =~ pattern ? :_alone : true }.each { |key, lines| pp lines } }
You can use the special symbol :_separator
or nil
to force an element to be ignored (not included in any chunk):
a = [0, 0, -1, 1, 1] e = a.chunk{|i| i < 0 ? :_separator : true } e.to_a # => [[true, [0, 0]], [true, [1, 1]]]
Note that the separator does end the chunk:
a = [0, 0, -1, 1, -1, 1] e = a.chunk{|i| i < 0 ? :_separator : true } e.to_a # => [[true, [0, 0]], [true, [1]], [true, [1]]]
For example, the sequence of hyphens in svn log can be eliminated as follows:
sep = "-"*72 + "\n" IO.popen("svn log README") { |f| f.chunk { |line| line != sep || nil }.each { |_, lines| pp lines } } #=> ["r20018 | knu | 2008-10-29 13:20:42 +0900 (Wed, 29 Oct 2008) | 2 lines\n", # "\n", # "* README, README.ja: Update the portability section.\n", # "\n"] # ["r16725 | knu | 2008-05-31 23:34:23 +0900 (Sat, 31 May 2008) | 2 lines\n", # "\n", # "* README, README.ja: Add a note about default C flags.\n", # "\n"] # ...
Paragraphs separated by empty lines can be parsed as follows:
File.foreach("README").chunk { |line| /\A\s*\z/ !~ line || nil }.each { |_, lines| pp lines }
With no block, returns a new array containing only unique elements; the array has no two elements e0
and e1
such that e0.eql?(e1)
:
%w[a b c c b a a b c].uniq # => ["a", "b", "c"] [0, 1, 2, 2, 1, 0, 0, 1, 2].uniq # => [0, 1, 2]
With a block, returns a new array containing elements only for which the block returns a unique value:
a = [0, 1, 2, 3, 4, 5, 5, 4, 3, 2, 1] a.uniq {|i| i.even? ? i : 0 } # => [0, 2, 4] a = %w[a b c d e e d c b a a b c d e] a.uniq {|c| c < 'c' } # => ["a", "c"]
Returns an array of all non-nil
elements:
a = [nil, 0, nil, 'a', false, nil, false, nil, 'a', nil, 0, nil] a.compact # => [0, "a", false, false, "a", 0]
Returns true if coverage stats are currently being collected (after Coverage.start
call, but before Coverage.result
call)
Returns system configuration directory.
This is typically "/etc"
, but is modified by the prefix used when Ruby was compiled. For example, if Ruby is built and installed in /usr/local
, returns "/usr/local/etc"
on other platforms than Windows.
On Windows, this always returns the directory provided by the system.