Returns the number of items in enum
through enumeration. If an argument is given, the number of items in enum
that are equal to item
are counted. If a block is given, it counts the number of elements yielding a true value.
ary = [1, 2, 4, 2] ary.count #=> 4 ary.count(2) #=> 2 ary.count{ |x| x%2==0 } #=> 3
Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or returns nil
otherwise.
If no block is given, an enumerator is returned instead.
(1..100).detect => #<Enumerator: 1..100:detect> (1..100).find => #<Enumerator: 1..100:find> (1..10).detect { |i| i % 5 == 0 and i % 7 == 0 } #=> nil (1..10).find { |i| i % 5 == 0 and i % 7 == 0 } #=> nil (1..100).detect { |i| i % 5 == 0 and i % 7 == 0 } #=> 35 (1..100).find { |i| i % 5 == 0 and i % 7 == 0 } #=> 35
Returns an array for all elements of enum
for which the given block
returns false
.
If no block is given, an Enumerator
is returned instead.
(1..10).reject { |i| i % 3 == 0 } #=> [1, 2, 4, 5, 7, 8, 10] [1, 2, 3, 4, 5].reject { |num| num.even? } #=> [1, 3, 5]
See also Enumerable#find_all
.
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 ==
.
IO.constants.include? :SEEK_SET #=> true IO.constants.include? :SEEK_NO_FURTHER #=> false IO.constants.member? :SEEK_SET #=> true IO.constants.member? :SEEK_NO_FURTHER #=> 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.
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.