Module: Enumerable

Defined in:
lib/mug/top.rb,
lib/mug/bool.rb,
lib/mug/enumerable/chain.rb,
lib/mug/enumerable/counts.rb,
lib/mug/enumerable/hash-like.rb,
lib/mug/enumerable/any-and-all.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.chain(*enums) ⇒ Enumerator, void

Note:

The instance method Enumerable#chain is provided as a polyfill for Ruby < 2.6. On Ruby 2.6+, the built-in Enumerable#chain (which returns a lazy Enumerator::Chain) is used instead.

Invokes a block once for every element in a sequence of Enumerables.

Examples:

require 'mug/enumerable/chain'
Enumerable.chain([1, 2], [3, 4]) {|x| puts x }
# prints 1, 2, 3, 4

Parameters:

Returns:

  • (Enumerator)

    if no block is given

  • (void)

    if a block is given



23
24
25
26
27
28
# File 'lib/mug/enumerable/chain.rb', line 23

def chain *enums
  return enum_for(:chain, *enums) unless block_given?
  enums.each do |enum|
    enum.each {|*args| yield(*args) }
  end
end

Instance Method Details

#any_and_all?(&block) ⇒ Boolean

Passes each element of the collection to the given block. The method returns true if the block contains elements that never return false or nil. If the block is not given, Ruby adds an implicit block of { |obj| obj } which will cause any_and_all? to return true when none of the collection members are false or nil.

Examples:

require 'mug/enumerable/any-and-all'
[1, 2, 3].any_and_all?        #=> true
[1, nil, 3].any_and_all?      #=> false
[].any_and_all?               #=> false
[2, 4, 6].any_and_all?(&:even?)  #=> true

Returns:

  • (Boolean)

    true if the collection is non-empty and all elements are truthy



19
20
21
22
23
24
25
26
27
28
# File 'lib/mug/enumerable/any-and-all.rb', line 19

def any_and_all? &block
  block ||= proc {|obj| obj }

  result = false
  each do |x|
    return false unless block[x]
    result = true
  end
  result
end

#bottom(n = 1) {|a, b| ... } ⇒ Array

Note:

bottom(n) is similar to Enumerable#min(n) (Ruby 2.2+).

Get the bottom n items, ordered from bottom to top.

Returns an Array even when n is 1.

Parameters:

  • n (Integer) (defaults to: 1)

    the number of items to return

Yields:

  • (a, b)

    optional comparison block

Yield Parameters:

  • a (Object)

    an element to compare

  • b (Object)

    an element to compare

Returns:

  • (Array)

    the bottom n items

See Also:

  • #sort


83
84
85
86
87
88
89
90
# File 'lib/mug/top.rb', line 83

def bottom n=1, &blk
  if block_given?
    sort(&blk)[0...n]
  else
    #bottom_by(n) {|x| x }
    sort[0...n]
  end
end

#bottom_by(n = 1) {|item| ... } ⇒ Array, Enumerator

Note:

Similar to Enumerable#min_by(n) (Ruby 2.2+), but guarantees stable ordering among tied elements.

Get the bottom n items, in order from bottom to top, ordered by mapping the values through the given block.

Returns an Array even when n is 1. Values that are tied after mapping are returned in the initial order.

If no block is given, an enumerator is returned instead.

Parameters:

  • n (Integer) (defaults to: 1)

    the number of items to return

Yields:

  • (item)

    mapping block

Yield Parameters:

  • item (Object)

    an element to map

Returns:

See Also:

  • #sort_by


112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/mug/top.rb', line 112

def bottom_by n=1, &_blk
  return enum_for(:bottom_by, n) unless block_given?
  chain = {}
  each do |x|
    y = yield x
    chain[y] ||= []
    chain[y] << x
  end
  ary = []
  chain.keys.sort.each do |k|
    ary += chain[k]
    break if ary.length > n
  end
  ary[0...n]
end

#counts(&block) ⇒ Hash

Note:

Similar to Enumerable#tally (Ruby 2.7+). Unlike tally, the returned hash has a default value of 0 for missing keys.

Returns a hash of item=>count showing how many of each item are in this Enumerable.

Examples:

require 'mug/enumerable/counts'
%w(a b b).counts  #=> {'a'=>1, 'b'=>2}

Returns:

  • (Hash)

    a hash mapping each item to its count, with a default value of 0



17
18
19
20
21
22
23
24
# File 'lib/mug/enumerable/counts.rb', line 17

def counts &block
  return counts_by(&block) if block_given?
  hsh = Hash.new{|h,k| h[k] = 0 }
  each do |k|
    hsh[k] += 1
  end
  hsh
end

#counts_by(&_block) ⇒ Hash, Enumerator

Note:

Similar to Enumerable#tally (Ruby 2.7+). Unlike tally, the returned hash has a default value of 0 for missing keys.

Passes each element in turn to the block, and returns a hash of result=>count.

If no block is given, an enumerator is returned.

Examples:

require 'mug/enumerable/counts'
%w(a b b).counts_by {|o| o.upcase }  #=> {'A'=>1, 'B'=>2}

Returns:

  • (Hash)

    a hash mapping each block result to its count, with a default value of 0

  • (Enumerator)

    if no block is given



42
43
44
45
46
47
48
49
50
# File 'lib/mug/enumerable/counts.rb', line 42

def counts_by &_block
  return enum_for(:counts_by) unless block_given?
  hsh = Hash.new{|h,k| h[k] = 0 }
  each do |j|
    k = yield j
    hsh[k] += 1
  end
  hsh
end

#each_keyObject

Calls block once for each key in the enum, passing the key as a parameter. If no block is given, an enumerator is returned instead.

@call-seq each_key {| key | block } -> hsh @call-seq each_key -> an_enumerator



23
24
25
26
27
28
# File 'lib/mug/enumerable/hash-like.rb', line 23

def each_key
  return enum_for(:each_key) unless block_given?

  # FIXME
  each_with_index {|_,i| yield i }
end

#each_pairObject

Calls block once for each key in the enum, passing the key-value pair as parameters. If no block is given, an enumerator is returned instead.

@call-seq each_pair {| key, value | block } -> hsh @call-seq each_pair -> an_enumerator



11
12
13
14
# File 'lib/mug/enumerable/hash-like.rb', line 11

def each_pair
  return enum_for(:each_pair) unless block_given?
  each_with_index {|e,i| yield i, e }
end

#fetch(*args) ⇒ Object

Returns a value from the enum for the given key. If the key can't be found, there are several options: With no other arguments, it will raise a KeyError exception; if default is given, then that will be returned; if the optional code block is specified, then that will be run and its result returned.

@call-seq fetch(key [, default] ) -> obj @call-seq fetch(key) { |key| block } -> obj

Raises:

  • (ArgumentError)


42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/mug/enumerable/hash-like.rb', line 42

def fetch *args
  raise ArgumentError, "incorrect number of arguments (#{args.length} for 1..2)" if args.length < 1 || args.length > 2
  key, default = *args

  each_pair do |k,v|
    return v if k == key
  end
  if args.length > 1
    default
  elsif block_given?
    yield key
  else
    raise KeyError, 'key not found'
  end
end

#fetch_values(*keys) ⇒ Object

Returns an array containing the values associated with the given keys but also raises KeyError when one of keys can't be found. Also see #values_at and #fetch.

@call-seq fetch_values(key, ...) -> array @call-seq fetch_values(key, ...) { |key| block } -> array



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/mug/enumerable/hash-like.rb', line 66

def fetch_values *keys
  key_map = {}
  keys.each_with_index do |key, index|
    key_map[key] ||= []
    key_map[key] << index
  end

  remain = keys.length
  result = [nil] * keys.length
  define = [nil] * keys.length

  each_pair do |k,v|
    break if remain < 1

    key_indices = key_map[k]
    next unless key_indices

    key_indices.each do |key_index|
      result[key_index] = v
      define[key_index] = true
      remain -= 1
    end
  end

  if remain > 0
    if block_given?
      define.each_with_index do |isdef, index|
        next if isdef
        result[index] = yield keys[index]
      end
    else
      index = define.index nil
      raise KeyError, "key not found: #{keys[index].inspect}"
    end
  end

  result
end

#key?(key) ⇒ Boolean Also known as: has_key?

Returns true if the given key is present in this enum.

@call-seq key?(key) -> true or false

Returns:

  • (Boolean)


112
113
114
# File 'lib/mug/enumerable/hash-like.rb', line 112

def key? key
  each_pair.find {|k, _| key == k } && true
end

#keysObject

Returns a new array populated with the keys from this enum.

@call-seq keys -> array



122
123
124
# File 'lib/mug/enumerable/hash-like.rb', line 122

def keys
  each_with_index.map {|_, index| index }
end

#lengthObject Also known as: size

Returns the number of key-value pairs in the hash.

@call-seq length -> integer



131
132
133
# File 'lib/mug/enumerable/hash-like.rb', line 131

def length
  reduce(0) {|sum,_| sum + 1 }
end

#member?(key) ⇒ Boolean

Returns true if the given key is present in this enum.

@call-seq member?(key) -> true or false

Returns:

  • (Boolean)


142
143
144
# File 'lib/mug/enumerable/hash-like.rb', line 142

def member? key
  fetch(key, nil) && true
end

#slice(*keys) ⇒ Object

Returns a hash containing only the given keys and their values.

@call-seq slice(*keys) -> a_hash



151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/mug/enumerable/hash-like.rb', line 151

def slice *keys
  missing = {}
  values = fetch_values(*keys) {|key| missing[key] = nil }

  result = {}
  values.each_with_index do |val, i|
    key = keys[i]
    next if missing.key? key
    next if result.key? key
    result[key] = val
  end
  result
end

#to_bBoolean

Converts enum to a boolean. Returns true if there are any elements.

Returns:

  • (Boolean)

    true if self contains any elements



136
137
138
# File 'lib/mug/bool.rb', line 136

def to_b
  any?{ true }
end

#top(n = 1) {|a, b| ... } ⇒ Array

Note:

top(n) is similar to Enumerable#max(n) (Ruby 2.2+).

Get the top n items, in order from top to bottom.

Returns an Array even when n is 1.

Parameters:

  • n (Integer) (defaults to: 1)

    the number of items to return

Yields:

  • (a, b)

    optional comparison block

Yield Parameters:

  • a (Object)

    an element to compare

  • b (Object)

    an element to compare

Returns:

  • (Array)

    the top n items

See Also:

  • #sort


19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/mug/top.rb', line 19

def top n=1, &_blk
  if block_given?
    sort{|x,y| yield y, x }[0...n]
  else
    #top_by(n) {|x| x }
    if n <= length
      sort[-n..-1].reverse
    else
      sort.reverse
    end
  end
end

#top_by(n = 1) {|item| ... } ⇒ Array, Enumerator

Note:

Similar to Enumerable#max_by(n) (Ruby 2.2+), but guarantees stable ordering among tied elements.

Get the top n items, in order from top to bottom, ordered by mapping the values through the given block.

Returns an Array even when n is 1. Values that are tied after mapping are returned in the initial order.

If no block is given, an enumerator is returned instead.

Parameters:

  • n (Integer) (defaults to: 1)

    the number of items to return

Yields:

  • (item)

    mapping block

Yield Parameters:

  • item (Object)

    an element to map

Returns:

See Also:

  • #sort_by


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/mug/top.rb', line 52

def top_by n=1, &_blk
  return enum_for(:top_by, n) unless block_given?
  chain = {}
  each do |x|
    y = yield x
    chain[y] ||= []
    chain[y] << x
  end
  ary = []
  chain.keys.sort.reverse.each do |k|
    ary += chain[k]
    break if ary.length > n
  end
  ary[0...n]
end

#transform_keysObject

Returns a new hash with the results of running the block once for every key. If no block is given, an enumerator is returned instead.

@call-seq transform_keys {|key| block } -> new_hash @call-seq transform_keys -> an_enumerator



172
173
174
175
176
177
178
179
180
# File 'lib/mug/enumerable/hash-like.rb', line 172

def transform_keys
  return enum_for(:transform_keys) unless block_given?
  result = {}
  each_pair do |key, value|
    newkey = yield key
    result[newkey] = value
  end
  result
end

#transform_valuesObject

Returns a new hash with the results of running the block once for every value. If no block is given, an enumerator is returned instead.

@call-seq transform_values {|value| block } -> new_hash @call-seq transform_values -> an_enumerator



189
190
191
192
193
194
195
196
197
# File 'lib/mug/enumerable/hash-like.rb', line 189

def transform_values
  return enum_for(:transform_values) unless block_given?
  result = {}
  each_pair do |key, value|
    newvalue = yield value
    result[key] = newvalue
  end
  result
end

#value?(value) ⇒ Boolean Also known as: has_value?

Returns true if the given value is present for some key.

@call-seq value?(value) -> true or false

Returns:

  • (Boolean)


204
205
206
# File 'lib/mug/enumerable/hash-like.rb', line 204

def value? value
  include? value
end

#valuesObject

Returns a new array populated with the values from this enum.

@call-seq values -> array



214
215
216
# File 'lib/mug/enumerable/hash-like.rb', line 214

def values
  to_a
end

#values_at(*keys) ⇒ Object

Return an array containing the values associated with the given keys.

@call-seq values_at(key, ...) -> array



223
224
225
# File 'lib/mug/enumerable/hash-like.rb', line 223

def values_at *keys
  fetch_values(*keys) {|key| nil }
end