Attempts to return an array, based on the given object
.
If object
is an array, returns object
.
Otherwise if object
responds to :to_ary
. calls object.to_ary
: if the return value is an array or nil
, returns that value; if not, raises TypeError
.
Otherwise returns nil
.
Related: see Methods for Creating an Array.
Replaces the elements of self
with the elements of other_array
, which must be an array-convertible object; returns self
:
a = ['a', 'b', 'c'] # => ["a", "b", "c"] a.replace(['d', 'e']) # => ["d", "e"]
Related: see Methods for Assigning.
With a block given, iterates over the elements of self
, passing each array index to the block; returns self
:
a = [:foo, 'bar', 2] a.each_index {|index| puts "#{index} #{a[index]}" }
Output:
0 foo 1 bar 2 2
Allows the array to be modified during iteration:
a = [:foo, 'bar', 2] a.each_index {|index| puts index; a.clear if index > 0 } a # => []
Output:
0 1
With no block given, returns a new Enumerator
.
Related: see Methods for Iterating.
With a block given, calls the block with each repeated combination of length size
of the elements of self
; each combination is an array; returns self
. The order of the combinations is indeterminate.
If a positive integer argument size
is given, calls the block with each size
-tuple repeated combination of the elements of self
. The number of combinations is (size+1)(size+2)/2
.
Examples:
size
is 1:
c = [] [0, 1, 2].repeated_combination(1) {|combination| c.push(combination) } c # => [[0], [1], [2]]
size
is 2:
c = [] [0, 1, 2].repeated_combination(2) {|combination| c.push(combination) } c # => [[0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2]]
If size
is zero, calls the block once with an empty array.
If size
is negative, does not call the block:
[0, 1, 2].repeated_combination(-1) {|combination| fail 'Cannot happen' }
With no block given, returns a new Enumerator
.
Related: see Methods for Combining.
Returns the integer index of the element from self
found by a binary search, or nil
if the search found no suitable element.
See Binary Searching.
Related: see Methods for Fetching.
If object
is an Integer object, returns object
.
Integer.try_convert(1) # => 1
Otherwise if object
responds to :to_int
, calls object.to_int
and returns the result.
Integer.try_convert(1.25) # => 1
Returns nil
if object
does not respond to :to_int
Integer.try_convert([]) # => nil
Raises an exception unless object.to_int
returns an Integer object.
Returns the number of bits of the value of self
, which is the bit position of the highest-order bit that is different from the sign bit (where the least significant bit has bit position 1). If there is no such bit (zero or minus one), returns zero.
This method returns ceil(log2(self < 0 ? -self : self + 1))
>.
(-2**1000-1).bit_length # => 1001 (-2**1000).bit_length # => 1000 (-2**1000+1).bit_length # => 1000 (-2**12-1).bit_length # => 13 (-2**12).bit_length # => 12 (-2**12+1).bit_length # => 12 -0x101.bit_length # => 9 -0x100.bit_length # => 8 -0xff.bit_length # => 8 -2.bit_length # => 1 -1.bit_length # => 0 0.bit_length # => 0 1.bit_length # => 1 0xff.bit_length # => 8 0x100.bit_length # => 9 (2**12-1).bit_length # => 12 (2**12).bit_length # => 13 (2**12+1).bit_length # => 13 (2**1000-1).bit_length # => 1000 (2**1000).bit_length # => 1001 (2**1000+1).bit_length # => 1001
For Integer n, this method can be used to detect overflow in Array#pack
:
if n.bit_length < 32 [n].pack('l') # No overflow. else raise 'Overflow' end
Returns self
(which is already an Integer).
Returns self
as an integer; converts using method to_i
in the derived class.
Of the Core and Standard Library classes, only Rational
and Complex
use this implementation.
Examples:
Rational(1, 2).to_int # => 0 Rational(2, 1).to_int # => 2 Complex(2, 0).to_int # => 2 Complex(2, 1).to_int # Raises RangeError (non-zero imaginary part)
Returns self
truncated to an Integer
.
1.2.to_i # => 1 (-1.2).to_i # => -1
Note that the limited precision of floating-point arithmetic may lead to surprising results:
(0.3 / 0.1).to_i # => 2 (!)
Like backtrace
, but returns each line of the execution stack as a Thread::Backtrace::Location
. Accepts the same arguments as backtrace
.
f = Fiber.new { Fiber.yield } f.resume loc = f.backtrace_locations.first loc.label #=> "yield" loc.path #=> "test.rb" loc.lineno #=> 1
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.
If file_name is writable by others, returns an integer representing the file permission bits of file_name. Returns nil
otherwise. The meaning of the bits is platform dependent; on Unix systems, see stat(2)
.
file_name can be an IO
object.
File.world_writable?("/tmp") #=> 511 m = File.world_writable?("/tmp") sprintf("%o", m) #=> "777"
Returns the list of available encoding names.
Encoding.name_list #=> ["US-ASCII", "ASCII-8BIT", "UTF-8", "ISO-8859-1", "Shift_JIS", "EUC-JP", "Windows-31J", "BINARY", "CP932", "eucJP"]
Returns default internal encoding. Strings will be transcoded to the default internal encoding in the following places if the default internal encoding is not nil:
CSV
File
data read from disk
Strings returned from Readline
Strings returned from SDBM
Values from ENV
Values in ARGV including $PROGRAM_NAME
Additionally String#encode
and String#encode!
use the default internal encoding if no encoding is given.
The script encoding (__ENCODING__), not default_internal
, is used as the encoding of created strings.
Encoding::default_internal
is initialized with -E option or nil otherwise.
Sets default internal encoding or removes default internal encoding when passed nil. You should not set Encoding::default_internal
in ruby code as strings created before changing the value may have a different encoding from strings created after the change. Instead you should use ruby -E
to invoke ruby with the correct default_internal.
See Encoding::default_internal
for information on how the default internal encoding is used.
Iterates the given block for each element with an index, which starts from offset
. If no block is given, returns a new Enumerator
that includes the index, starting from offset
offset
the starting index to use
Returns the list of private methods accessible to obj. If the all parameter is set to false
, only those methods in the receiver will be listed.
Returns true
if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.
module M; end class A include M end class B < A; end class C < B; end b = B.new b.is_a? A #=> true b.is_a? B #=> true b.is_a? C #=> false b.is_a? M #=> true b.kind_of? A #=> true b.kind_of? B #=> true b.kind_of? C #=> false b.kind_of? M #=> true
Returns the backtrace (the list of code locations that led to the exception), as an array of Thread::Backtrace::Location
instances.
Example (assuming the code is stored in the file named t.rb
):
def division(numerator, denominator) numerator / denominator end begin division(1, 0) rescue => ex p ex.backtrace_locations # ["t.rb:2:in 'Integer#/'", "t.rb:2:in 'Object#division'", "t.rb:6:in '<main>'"] loc = ex.backtrace_locations.first p loc.class # Thread::Backtrace::Location p loc.path # "t.rb" p loc.lineno # 2 p loc.label # "Integer#/" end
The value returned by this method might be adjusted when raising (see Kernel#raise
), or during intermediate handling by set_backtrace
.
See also backtrace
that provide the same value as an array of strings. (Note though that two values might not be consistent with each other when backtraces are manually adjusted.)
See Backtraces.
Sets the backtrace value for self
; returns the given value
.
The value
might be:
an array of Thread::Backtrace::Location
;
an array of String
instances;
a single String
instance; or
nil
.
Using array of Thread::Backtrace::Location
is the most consistent option: it sets both backtrace
and backtrace_locations
. It should be preferred when possible. The suitable array of locations can be obtained from Kernel#caller_locations
, copied from another error, or just set to the adjusted result of the current error’s backtrace_locations
:
require 'json' def parse_payload(text) JSON.parse(text) # test.rb, line 4 rescue JSON::ParserError => ex ex.set_backtrace(ex.backtrace_locations[2...]) raise end parse_payload('{"wrong: "json"') # test.rb:4:in 'Object#parse_payload': unexpected token at '{"wrong: "json"' (JSON::ParserError) # # An error points to the body of parse_payload method, # hiding the parts of the backtrace related to the internals # of the "json" library # The error has both #backtace and #backtrace_locations set # consistently: begin parse_payload('{"wrong: "json"') rescue => ex p ex.backtrace # ["test.rb:4:in 'Object#parse_payload'", "test.rb:20:in '<main>'"] p ex.backtrace_locations # ["test.rb:4:in 'Object#parse_payload'", "test.rb:20:in '<main>'"] end
When the desired stack of locations is not available and should be constructed from scratch, an array of strings or a singular string can be used. In this case, only backtrace
is affected:
def parse_payload(text) JSON.parse(text) rescue JSON::ParserError => ex ex.set_backtrace(["dsl.rb:34", "framework.rb:1"]) # The error have the new value in #backtrace: p ex.backtrace # ["dsl.rb:34", "framework.rb:1"] # but the original one in #backtrace_locations p ex.backtrace_locations # [".../json/common.rb:221:in 'JSON::Ext::Parser.parse'", ...] end parse_payload('{"wrong: "json"')
Calling set_backtrace
with nil
clears up backtrace
but doesn’t affect backtrace_locations
:
def parse_payload(text) JSON.parse(text) rescue JSON::ParserError => ex ex.set_backtrace(nil) p ex.backtrace # nil p ex.backtrace_locations # [".../json/common.rb:221:in 'JSON::Ext::Parser.parse'", ...] end parse_payload('{"wrong: "json"')
On reraising of such an exception, both backtrace
and backtrace_locations
is set to the place of reraising:
def parse_payload(text) JSON.parse(text) rescue JSON::ParserError => ex ex.set_backtrace(nil) raise # test.rb, line 7 end begin parse_payload('{"wrong: "json"') rescue => ex p ex.backtrace # ["test.rb:7:in 'Object#parse_payload'", "test.rb:11:in '<main>'"] p ex.backtrace_locations # ["test.rb:7:in 'Object#parse_payload'", "test.rb:11:in '<main>'"] end
See Backtraces.