The string representation of false
is “false”.
Returns the unique identifier for this proc, along with an indication of where the proc was defined.
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#+(_)>""
Dissociates meth from its current receiver. The resulting UnboundMethod
can subsequently be bound to a new object of the same class (see UnboundMethod
).
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#+(_)>""
Bind umeth to obj. If Klass was the class from which umeth was obtained, obj.kind_of?(Klass)
must be true.
class A def test puts "In test, class = #{self.class}" end end class B < A end class C < B end um = B.instance_method(:test) bm = um.bind(C.new) bm.call bm = um.bind(B.new) bm.call bm = um.bind(A.new) bm.call
produces:
In test, class = C In test, class = B prog.rb:16:in `bind': bind argument must be an instance of B (TypeError) from prog.rb:16
The calling thread will suspend execution and run this thr
.
Does not return until thr
exits or until the given limit
seconds have passed.
If the time limit expires, nil
will be returned, otherwise thr
is returned.
Any threads not joined will be killed when the main program exits.
If thr
had previously raised an exception and the ::abort_on_exception
or $DEBUG flags are not set, (so the exception has not yet been processed), it will be processed at this time.
a = Thread.new { print "a"; sleep(10); print "b"; print "c" } x = Thread.new { print "x"; Thread.pass; print "y"; print "z" } x.join # Let thread x finish, thread a will be killed on exit. #=> "axyz"
The following example illustrates the limit
parameter.
y = Thread.new { 4.times { sleep 0.1; puts 'tick... ' }} puts "Waiting" until y.join(0.15)
This will produce:
tick... Waiting tick... Waiting tick... tick...
Dump the name, id, and status of thr to a string.
Return a string containing a human-readable TracePoint
status.
Line number of the event
Equivalent to:
io.write(sprintf(format_string, *objects))
For details on format_string
, see Format Specifications.
With the single argument format_string
, formats objects
into the string, then writes the formatted string to $stdout:
printf('%4.4d %10s %2.2f', 24, 24, 24.0)
Output (on $stdout):
0024 24 24.00#
With arguments io
and format_string
, formats objects
into the string, then writes the formatted string to io
:
printf($stderr, '%4.4d %10s %2.2f', 24, 24, 24.0)
Output (on $stderr):
0024 24 24.00# => nil
With no arguments, does nothing.
Equivalent to $stdout.print(*objects)
, this method is the straightforward way to write to $stdout
.
Writes the given objects to $stdout
; returns nil
. Appends the output record separator $OUTPUT_RECORD_SEPARATOR
$\
), if it is not nil
.
With argument objects
given, for each object:
Converts via its method to_s
if not a string.
Writes to stdout
.
If not the last object, writes the output field separator $OUTPUT_FIELD_SEPARATOR
($,
if it is not nil
.
With default separators:
objects = [0, 0.0, Rational(0, 1), Complex(0, 0), :zero, 'zero'] $OUTPUT_RECORD_SEPARATOR $OUTPUT_FIELD_SEPARATOR print(*objects)
Output:
nil nil 00.00/10+0izerozero
With specified separators:
$OUTPUT_RECORD_SEPARATOR = "\n" $OUTPUT_FIELD_SEPARATOR = ',' print(*objects)
Output:
0,0.0,0/1,0+0i,zero,zero
With no argument given, writes the content of $_
(which is usually the most recent user input):
gets # Sets $_ to the most recent user input. print # Prints $_.
Equivalent to method Kernel#gets
, except that it raises an exception if called at end-of-stream:
$ cat t.txt | ruby -e "p readlines; readline" ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"] in `readline': end of file reached (EOFError)
Optional keyword argument chomp
specifies whether line separators are to be omitted.
Returns an array containing the lines returned by calling Kernel#gets
until the end-of-stream is reached; (see Line IO).
With only string argument sep
given, returns the remaining lines as determined by line separator sep
, or nil
if none; see Line Separator:
# Default separator. $ cat t.txt | ruby -e "p readlines" ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"] # Specified separator. $ cat t.txt | ruby -e "p readlines 'li'" ["First li", "ne\nSecond li", "ne\n\nFourth li", "ne\nFifth li", "ne\n"] # Get-all separator. $ cat t.txt | ruby -e "p readlines nil" ["First line\nSecond line\n\nFourth line\nFifth line\n"] # Get-paragraph separator. $ cat t.txt | ruby -e "p readlines ''" ["First line\nSecond line\n\n", "Fourth line\nFifth line\n"]
With only integer argument limit
given, limits the number of bytes in the line; see Line Limit:
$cat t.txt | ruby -e "p readlines 10" ["First line", "\n", "Second lin", "e\n", "\n", "Fourth lin", "e\n", "Fifth line", "\n"] $cat t.txt | ruby -e "p readlines 11" ["First line\n", "Second line", "\n", "\n", "Fourth line", "\n", "Fifth line\n"] $cat t.txt | ruby -e "p readlines 12" ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]
With arguments sep
and limit
given, combines the two behaviors (see Line Separator and Line Limit).
Optional keyword argument chomp
specifies whether line separators are to be omitted:
$ cat t.txt | ruby -e "p readlines(chomp: true)" ["First line", "Second line", "", "Fourth line", "Fifth line"]
Optional keyword arguments enc_opts
specify encoding options; see Encoding options.
Returns an integer converted from object
.
Tries to convert object
to an integer using to_int
first and to_i
second; see below for exceptions.
With a non-zero base
, object
must be a string or convertible to a string.
With integer argument object
given, returns object
:
Integer(1) # => 1 Integer(-1) # => -1
With floating-point argument object
given, returns object
truncated to an integer:
Integer(1.9) # => 1 # Rounds toward zero. Integer(-1.9) # => -1 # Rounds toward zero.
With string argument object
and zero base
given, returns object
converted to an integer in base 10:
Integer('100') # => 100 Integer('-100') # => -100
With base
zero, string object
may contain leading characters to specify the actual base (radix indicator):
Integer('0100') # => 64 # Leading '0' specifies base 8. Integer('0b100') # => 4 # Leading '0b', specifies base 2. Integer('0x100') # => 256 # Leading '0x' specifies base 16.
With a positive base
(in range 2..36) given, returns object
converted to an integer in the given base:
Integer('100', 2) # => 4 Integer('100', 8) # => 64 Integer('-100', 16) # => -256
With a negative base
(in range -36..-2) given, returns object
converted to an integer in the radix indicator if exists or -base
:
Integer('0x100', -2) # => 256 Integer('100', -2) # => 4 Integer('0b100', -8) # => 4 Integer('100', -8) # => 64 Integer('0o100', -10) # => 64 Integer('100', -10) # => 100
base
-1 is equal the -10 case.
When converting strings, surrounding whitespace and embedded underscores are allowed and ignored:
Integer(' 100 ') # => 100 Integer('-1_0_0', 16) # => -256
Examples with object
of various other classes:
Integer(Rational(9, 10)) # => 0 # Rounds toward zero. Integer(Complex(2, 0)) # => 2 # Imaginary part must be zero. Integer(Time.now) # => 1650974042
With optional keyword argument exception
given as true
(the default):
Raises TypeError
if object
does not respond to to_int
or to_i
.
Raises TypeError
if object
is nil
.
Raise ArgumentError
if object
is an invalid string.
With exception
given as false
, an exception of any kind is suppressed and nil
is returned.
Returns the string resulting from formatting objects
into format_string
.
For details on format_string
, see Format Specifications.
Returns the string resulting from formatting objects
into format_string
.
For details on format_string
, see Format Specifications.
Returns a string converted from object
.
Tries to convert object
to a string using to_str
first and to_s
second:
String([0, 1, 2]) # => "[0, 1, 2]" String(0..5) # => "0..5" String({foo: 0, bar: 1}) # => "{:foo=>0, :bar=>1}"
Raises TypeError
if object
cannot be converted to a string.
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 returned by the block.
With a block given, calls the block with successive elements; returns an array of the objects returned by the block:
(0..4).map {|i| i*i } # => [0, 1, 4, 9, 16] {foo: 0, bar: 1, baz: 2}.map {|key, value| value*2} # => [0, 2, 4]
With no block given, returns an Enumerator
.
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 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
Returns an enumerator object generated from this enumerator and given enumerables.
e = (1..3).chain([4, 5]) e.to_a #=> [1, 2, 3, 4, 5]
Returns true if coverage stats are currently being collected (after Coverage.start
call, but before Coverage.result
call)