- Enumerable
- all?
- any?
- chunk
- chunk_while?
- collect
- collect_concat
- count
- cycle
- detect
- drop
- drop_while
- each_cons
- each_entry
- each_slice
- each_with_index
- each_with_object
- entries
- find
- find_all
- find_index
- first
- flat_map
- grep
- grep_v
- group_by
- include?
- inject
- lazy
- map
- max
- max_by
- member?
- min
- min_by
- minmax
- minmax_by
- none?
- one?
- partition
- reduce
- reject also see find_all
- reverse_each
- select also see reject
%w[ant bear cat].all? { |word| word.length >= 3 }
%w[ant bear cat].any? { |word| word.length >= 3 } #=> true
arrChunks = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5].chunk { |n| n.even?}
arrChunks.each {|bool, arr| puts [bool, arr] }
a = [1,2,4,9,10,11,12,15,16,19,20,21]
b = a.chunk_while {|i, j| i+1 == j }
p b.to_a #=> [[1, 2], [4], [9, 10, 11, 12], [15, 16], [19, 20, 21]]
c = b.map {|a| a.length < 3 ? a : "#{a.first}-#{a.last}" }
p c #=> [[1, 2], [4], "9-12", [15, 16], "19-21"]
d = c.join(",")
p d #=> "1,2,4,9-12,15,16,19-21"
a = [0, 9, 2, 2, 3, 2, 7, 5, 9, 5]
p a.chunk_while {|i, j| i <= j }.to_a
#=> [[0, 9], [2, 2, 3], [2, 7], [5, 9], [5]]
Take me there
a = [7, 5, 9, 2, 0, 7, 9, 4, 2, 0]
p a.chunk_while {|i, j| i.even? == j.even? }.to_a
#=> [[7, 5, 9], [2, 0], [7, 9], [4, 2, 0]]
(1..4).map { |i| i*i } #=> [1, 4, 9, 16]
(1..4).collect { "cat" } #=> ["cat", "cat", "cat", "cat"]
[1, 2, 3, 4].flat_map { |e| [e, -e] } #=> [1, -1, 2, -2, 3, -3, 4, -4]
[[1, 2], [3, 4]].flat_map { |e| e + [100] } #=> [1, 2, 100, 3, 4, 100]
ary = [1, 2, 4, 2]
ary.count #=> 4
ary.count(2) #=> 2
ary.count{ |x| x%2==0 } #=> 3
a = ["a", "b", "c"]
a.cycle { |x| puts x } # print, a, b, c, a, b, c,.. forever.
a.cycle(2) { |x| puts x } # print, a, b, c, a, b, c.
(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
a = [1, 2, 3, 4, 5, 0]
a.drop(3) #=> [4, 5, 0]
-
Drops elements up to, but not including, the first element for which the block returns nil or false and returns an array containing the remaining elements.
-
If no block is given, an enumerator is returned instead.
a = [1, 2, 3, 4, 5, 0]
a.drop_while { |i| i < 3 } #=> [3, 4, 5, 0]
- Iterates the given block for each array of consecutive elements. If no block is given, returns an enumerator.
(1..10).each_cons(3) { |a| p a }
# outputs below
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]
[7, 8, 9]
[8, 9, 10]
-
Calls block once for each element in self, passing that element as a parameter, converting multiple values from yield to an array.
-
If no block is given, an enumerator is returned instead.
class Foo
include Enumerable
def each
yield 1
yield 1, 2
yield
end
end
Foo.new.each_entry{ |o| p o }
# product
1
[1, 2]
nil
(1..10).each_slice(3) { |a| p a }
# outputs below
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10]
-
Calls block with two arguments, the item and its index, for each item in enum. Given arguments are passed through to each().
-
If no block is given, an enumerator is returned instead.
hash = Hash.new
%w(cat dog wombat).each_with_index { |item, index|
hash[item] = index
}
hash #=> {"cat"=>0, "dog"=>1, "wombat"=>2}
-
Iterates the given block for each element with an arbitrary object given, and returns the initially given object.
-
If no block is given, returns an enumerator.
evens = (1..10).each_with_object([]) { |i, a| a << i*2 }
#=> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
- Returns an array containing the items in enum.
(1..7).to_a #=> [1, 2, 3, 4, 5, 6, 7]
{ 'a'=>1, 'b'=>2, 'c'=>3 }.to_a #=> [["a", 1], ["b", 2], ["c", 3]]
require 'prime'
Prime.entries 10 #=> [2, 3, 5, 7]
-
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
(1..10).find_all { |i| i % 3 == 0 } #=> [3, 6, 9]
[1,2,3,4,5].select { |num| num.even? } #=> [2, 4]
-
Compares each entry in enum with value or passes to block. Returns the index for the first for which the evaluated value is non-false. If no object matches, returns nil
-
If neither block nor argument is given, an enumerator is returned instead.
(1..10).find_index { |i| i % 5 == 0 and i % 7 == 0 } #=> nil
(1..100).find_index { |i| i % 5 == 0 and i % 7 == 0 } #=> 34
(1..100).find_index(50) #=> 49
%w[foo bar baz].first #=> "foo"
%w[foo bar baz].first(2) #=> ["foo", "bar"]
%w[foo bar baz].first(10) #=> ["foo", "bar", "baz"]
[].first #=> nil
[].first(10) #=> []
[1, 2, 3, 4].flat_map { |e| [e, -e] } #=> [1, -1, 2, -2, 3, -3, 4, -4]
[[1, 2], [3, 4]].flat_map { |e| e + [100] } #=> [1, 2, 100, 3, 4, 100]
- Returns an array of every element in enum for which Pattern === element. If the optional block is supplied, each matching element is passed to it, and the block’s result is stored in the output array
(1..100).grep 38..44 #=> [38, 39, 40, 41, 42, 43, 44]
c = IO.constants
c.grep(/SEEK/) #=> [:SEEK_SET, :SEEK_CUR, :SEEK_END]
res = c.grep(/SEEK/) { |v| IO.const_get(v) }
res #=> [0, 1, 2]
- Inverted version of #grep. Returns an array of every element in enum for which not Pattern === element.
(1..10).grep_v 2..5 #=> [1, 6, 7, 8, 9, 10]
res =(1..10).grep_v(2..5) { |v| v * 2 }
res #=> [2, 12, 14, 16, 18, 20]
-
Groups the collection by result of the block. Returns a hash where the keys are the evaluated result from the block and the values are arrays of elements in the collection that correspond to the key.
-
If no block is given an enumerator is returned.
(1..6).group_by { |i| i%3 } #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]}
- 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
# 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"
- Returns a lazy enumerator, whose methods map/collect, flat_map/collect_concat, select/find_all, reject, grep, #grep_v, zip, take, #take_while, drop, and #drop_while enumerate values only on an as-needed basis. However, if a block is given to zip, values are enumerated immediately.
def pythagorean_triples
(1..Float::INFINITY).lazy.flat_map {|z|
(1..z).flat_map {|x|
(x..z).select {|y|
x**2 + y**2 == z**2
}.map {|y|
[x, y, z]
}
}
}
end
# show first ten pythagorean triples
p pythagorean_triples.take(10).force # take is lazy, so force is needed
p pythagorean_triples.first(10) # first is eager
# show pythagorean triples less than 100
p pythagorean_triples.take_while { |*, z| z < 100 }.force
(1..4).map { |i| i*i } #=> [1, 4, 9, 16]
(1..4).collect { "cat" } #=> ["cat", "cat", "cat", "cat"]
- Returns the object in enum with the maximum value. The first form assumes all objects implement Comparable; the second uses the block to return a <=> b.
- If the n argument is given, maximum n elements are returned as an array, sorted in descending order.
a = %w(albatross dog horse)
a.max #=> "horse"
a.max { |a, b| a.length <=> b.length } #=> "albatross"
- If the n argument is given, maximum n elements are returned as an array, sorted in descending order.
a = %w[albatross dog horse]
a.max(2) #=> ["horse", "dog"]
a.max(2) {|a, b| a.length <=> b.length } #=> ["albatross", "horse"]
[5, 1, 3, 4, 2].max(3) #=> [5, 4, 3]
-
Returns the object in enum that gives the maximum value from the given block.
-
If no block is given, an enumerator is returned instead.
a = %w(albatross dog horse)
a.max_by { |x| x.length } #=> "albatross"
- If the n argument is given, maximum n elements are returned as an array. These n elements are sorted by the value from the given block, in descending order.
a = %w[albatross dog horse]
a.max_by(2) {|x| x.length } #=> ["albatross", "horse"]
- enum.max_by(n) can be used to implement weighted random sampling. Following example implements and use Enumerable#wsample.
module Enumerable
# weighted random sampling.
#
# Pavlos S. Efraimidis, Paul G. Spirakis
# Weighted random sampling with a reservoir
# Information Processing Letters
# Volume 97, Issue 5 (16 March 2006)
def wsample(n)
self.max_by(n) {|v| rand ** (1.0/yield(v)) }
end
end
e = (-20..20).to_a*10000
a = e.wsample(20000) {|x|
Math.exp(-(x/5.0)**2) # normal distribution
}
# a is 20000 samples from e.
p a.length #=> 20000
h = a.group_by {|x| x }
-10.upto(10) {|x| puts "*" * (h[x].length/30.0).to_i if h[x] }
#=> *
# ***
# ******
# ***********
# ******************
# *****************************
# *****************************************
# ****************************************************
# ***************************************************************
# ********************************************************************
# ***********************************************************************
# ***********************************************************************
# **************************************************************
# ****************************************************
# ***************************************
# ***************************
# ******************
# ***********
# *******
# ***
# *
- 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
- Returns the object in enum with the minimum value. The first form assumes all objects implement Comparable; the second uses the block to return a <=> b.
a = %w(albatross dog horse)
a.min #=> "albatross"
a.min { |a, b| a.length <=> b.length } #=> "dog"
- If the n argument is given, minimum n elements are returned as a sorted array.
a = %w[albatross dog horse]
a.min(2) #=> ["albatross", "dog"]
a.min(2) {|a, b| a.length <=> b.length } #=> ["dog", "horse"]
[5, 1, 3, 4, 2].min(3) #=> [1, 2, 3]
-
Returns the object in enum that gives the minimum value from the given block.
-
If no block is given, an enumerator is returned instead.
a = %w(albatross dog horse)
a.min_by { |x| x.length } #=> "dog"
- If the n argument is given, minimum n elements are returned as an array. These n elements are sorted by the value from the given block.
a = %w[albatross dog horse]
p a.min_by(2) {|x| x.length } #=> ["dog", "horse"]
- Returns a two element array which contains the minimum and the maximum value in the enumerable. The first form assumes all objects implement Comparable; the second uses the block to return a <=> b.
a = %w(albatross dog horse)
a.minmax #=> ["albatross", "horse"]
a.minmax { |a, b| a.length <=> b.length } #=> ["dog", "albatross"]
-
Returns a two element array containing the objects in enum that correspond to the minimum and maximum values respectively from the given block.
-
If no block is given, an enumerator is returned instead.
a = %w(albatross dog horse)
a.minmax_by { |x| x.length } #=> ["dog", "albatross"]
- 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.
%w{ant bear cat}.none? { |word| word.length == 5 } #=> true
%w{ant bear cat}.none? { |word| word.length >= 4 } #=> false
[].none? #=> true
[nil].none? #=> true
[nil, false].none? #=> true
[nil, false, true].none? #=> false
- 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.
%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
[ nil, true, 99 ].one? #=> false
[ nil, true, false ].one? #=> true
-
Returns two arrays, the first containing the elements of enum for which the block evaluates to true, the second containing the rest.
-
If no block is given, an enumerator is returned instead.
(1..6).partition { |v| v.even? } #=> [[2, 4, 6], [1, 3, 5]]
-
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"
-
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 find_all.
-
Builds a temporary array and traverses that array in reverse order.
-
If no block is given, an enumerator is returned instead.
(1..3).reverse_each { |v| p v }
produces:
3
2
1
-
Returns an array containing all elements of enum for which the given block returns a true value.
-
If no block is given, an Enumerator is returned instead
(1..10).find_all { |i| i % 3 == 0 } #=> [3, 6, 9]
[1,2,3,4,5].select { |num| num.even? } #=> [2, 4]
See also reject