Combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator.
The inject and reduce methods are aliases. There is no performance benefit to either.
If you specify a block, then for each element in enum the block is passed an accumulator value (memo) and the element. If you specify a symbol instead, then each element in the collection will be passed to the named method of memo. In either case, the result becomes the new value for memo. At the end of the iteration, the final value of memo is the return value for the method.
If you do not explicitly specify an initial value for memo, then the first element of collection is used as the initial value of memo.
# Sum some numbers (5..10).reduce(:+) #=> 45 # Same using a block and inject (5..10).inject { |sum, n| sum + n } #=> 45 # Multiply some numbers (5..10).reduce(1, :*) #=> 151200 # Same using a block (5..10).inject(1) { |product, n| product * n } #=> 151200 # find the longest word longest = %w{ cat sheep bear }.inject do |memo, word| memo.length > word.length ? memo : word end longest #=> "sheep"
Passes each element of the collection to the given block. The method returns true
if the block returns true
exactly once. If the block is not given, one?
will return true
only if exactly one of the collection members is true.
If instead a pattern is supplied, the method returns whether pattern === element
for exactly one collection member.
%w{ant bear cat}.one? { |word| word.length == 4 } #=> true %w{ant bear cat}.one? { |word| word.length > 4 } #=> false %w{ant bear cat}.one? { |word| word.length < 4 } #=> false %w{ant bear cat}.one?(/t/) #=> false [ nil, true, 99 ].one? #=> false [ nil, true, false ].one? #=> true [ nil, true, 99 ].one?(Integer) #=> true [].one? #=> false
Passes each element of the collection to the given block. The method returns true
if the block never returns true
for all elements. If the block is not given, none?
will return true
only if none of the collection members is true.
If instead a pattern is supplied, the method returns whether pattern === element
for none of the collection members.
%w{ant bear cat}.none? { |word| word.length == 5 } #=> true %w{ant bear cat}.none? { |word| word.length >= 4 } #=> false %w{ant bear cat}.none?(/d/) #=> true [1, 3.14, 42].none?(Float) #=> false [].none? #=> true [nil].none? #=> true [nil, false].none? #=> true [nil, false, true].none? #=> false
Returns true
if any member of enum equals obj. Equality is tested using ==
.
(1..10).include? 5 #=> true (1..10).include? 15 #=> false (1..10).member? 5 #=> true (1..10).member? 15 #=> false
Enumerates over the items, chunking them together based on the return value of the block.
Consecutive elements which return the same block value are chunked together.
For example, consecutive even numbers and odd numbers can be chunked as follows.
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5].chunk { |n| n.even? }.each { |even, ary| p [even, ary] } #=> [false, [3, 1]] # [true, [4]] # [false, [1, 5, 9]] # [true, [2, 6]] # [false, [5, 3, 5]]
This method is especially useful for sorted series of elements. The following example counts words for each initial letter.
open("/usr/share/dict/words", "r:iso-8859-1") { |f| f.chunk { |line| line.ord }.each { |ch, lines| p [ch.chr, lines.length] } } #=> ["\n", 1] # ["A", 1327] # ["B", 1372] # ["C", 1507] # ["D", 791] # ...
The following key values have special meaning:
nil
and :_separator
specifies that the elements should be dropped.
:_alone
specifies that the element should be chunked by itself.
Any other symbols that begin with an underscore will raise an error:
items.chunk { |item| :_underscore } #=> RuntimeError: symbols beginning with an underscore are reserved
nil
and :_separator
can be used to ignore some elements.
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 }
:_alone
can be used to force items into their own chunk. For example, you can put lines that contain a URL by themselves, and chunk the rest of the lines together, like this:
pattern = /http/ open(filename) { |f| f.chunk { |line| line =~ pattern ? :_alone : true }.each { |key, lines| pp lines } }
If no block is given, an enumerator to ‘chunk` is returned instead.
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.
Returns the system information obtained by uname system call.
The return value is a hash which has 5 keys at least:
:sysname, :nodename, :release, :version, :machine
Example:
require 'etc' require 'pp' pp Etc.uname #=> {:sysname=>"Linux", # :nodename=>"boron", # :release=>"2.6.18-6-xen-686", # :version=>"#1 SMP Thu Nov 5 19:54:42 UTC 2009", # :machine=>"i686"}
Returns system configuration variable using sysconf().
name should be a constant under Etc
which begins with SC_
.
The return value is an integer or nil. nil means indefinite limit. (sysconf() returns -1 but errno is not set.)
Etc.sysconf(Etc::SC_ARG_MAX) #=> 2097152 Etc.sysconf(Etc::SC_LOGIN_NAME_MAX) #=> 256
Returns system configuration variable using confstr().
name should be a constant under Etc
which begins with CS_
.
The return value is a string or nil. nil means no configuration-defined value. (confstr() returns 0 but errno is not set.)
Etc.confstr(Etc::CS_PATH) #=> "/bin:/usr/bin" # GNU/Linux Etc.confstr(Etc::CS_GNU_LIBC_VERSION) #=> "glibc 2.18" Etc.confstr(Etc::CS_GNU_LIBPTHREAD_VERSION) #=> "NPTL 2.18"
Returns the hexadecimal representation of a memory pointer address addr
Example:
lib = Fiddle.dlopen('/lib64/libc-2.15.so') => #<Fiddle::Handle:0x00000001342460> lib['strcpy'].to_s(16) => "7f59de6dd240" Fiddle.dlunwrap(Fiddle.dlwrap(lib['strcpy'].to_s(16))) => "7f59de6dd240"
Encodes string using Ruby’s String.encode
Returns an inspect() string summarizing the object state.
Returns self, for backward compatibility.
Decode the given gzipped string
.
This method is almost equivalent to the following code:
def gunzip(string) sio = StringIO.new(string) gz = Zlib::GzipReader.new(sio, encoding: Encoding::ASCII_8BIT) gz.read ensure gz&.close end
See also Zlib.gzip
Returns true
if the named file is a directory, or a symlink that points at a directory, and false
otherwise.
file_name can be an IO
object.
File.directory?(".")
Returns true
if the named file has the sticky bit set.
file_name can be an IO
object.
Returns true
if the named files are identical.
file_1 and file_2 can be an IO
object.
open("a", "w") {} p File.identical?("a", "a") #=> true p File.identical?("a", "./a") #=> true File.link("a", "b") p File.identical?("a", "b") #=> true File.symlink("a", "c") p File.identical?("a", "c") #=> true open("d", "w") {} p File.identical?("a", "d") #=> false
The number of times GC
occurred.
It returns the number of times GC
occurred since the process started.
Invokes the block with a Benchmark::Report object, which may be used to collect and report on the results of individual benchmark tests. Reserves label_width
leading spaces for labels on each line. Prints caption
at the top of the report, and uses format
to format each line. Returns an array of Benchmark::Tms
objects.
If the block returns an array of Benchmark::Tms
objects, these will be used to format additional lines of output. If labels
parameter are given, these are used to label these extra lines.
Note: Other methods provide a simpler interface to this one, and are suitable for nearly all benchmarking requirements. See the examples in Benchmark
, and the bm
and bmbm
methods.
Example:
require 'benchmark' include Benchmark # we need the CAPTION and FORMAT constants n = 5000000 Benchmark.benchmark(CAPTION, 7, FORMAT, ">total:", ">avg:") do |x| tf = x.report("for:") { for i in 1..n; a = "1"; end } tt = x.report("times:") { n.times do ; a = "1"; end } tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end } [tf+tt+tu, (tf+tt+tu)/3] end
Generates:
user system total real for: 0.970000 0.000000 0.970000 ( 0.970493) times: 0.990000 0.000000 0.990000 ( 0.989542) upto: 0.970000 0.000000 0.970000 ( 0.972854) >total: 2.930000 0.000000 2.930000 ( 2.932889) >avg: 0.976667 0.000000 0.976667 ( 0.977630)
Returns the elapsed real time used to execute the given block.