Returns self
.
Sorts the elements of self
in place, using an ordering determined by the block; returns self.
Calls the block with each successive element; sorts elements based on the values returned from the block.
For duplicates returned by the block, the ordering is indeterminate, and may be unstable.
This example sorts strings based on their sizes:
a = ['aaaa', 'bbb', 'cc', 'd'] a.sort_by! {|element| element.size } a # => ["d", "cc", "bbb", "aaaa"]
Returns a new Enumerator
if no block given:
a = ['aaaa', 'bbb', 'cc', 'd'] a.sort_by! # => #<Enumerator: ["aaaa", "bbb", "cc", "d"]:sort_by!>
Searches self
as described at method bsearch
, but returns the index of the found element instead of the element itself.
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
Imports methods from modules. Unlike Module#include
, Refinement#import_methods
copies methods and adds them into the refinement, so the refinement is activated in the imported methods.
Note that due to method copying, only methods defined in Ruby code can be imported.
module StrUtils def indent(level) ' ' * level + self end end module M refine String do import_methods StrUtils end end using M "foo".indent(3) #=> " foo" module M refine String do import_methods Enumerable # Can't import method which is not defined with Ruby code: Enumerable#drop end end