Module: Enumerable

Defined in:
lib/webget_ruby_ramp/enumerable.rb

Overview

Enumberable extensions

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.cartesian_product(*enums) ⇒ Array

This is the fastest implementation we have found. It returns results in typical order.

For our benchmarks, we also compared these:

Returns:

  • (Array)

    the cartesian product of the enumerations.

See Also:

Author:

  • Thomas Hafner



406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/webget_ruby_ramp/enumerable.rb', line 406

def self.cartesian_product(*enums)
  result = [[]]
  while [] != enums
    t, result = result, []
    b, *enums = enums
    t.each do |a|
      b.each do |n|
        result << a + [n]
      end
    end
  end
  result
end

Instance Method Details

#bisectArray<Array<Object>] an array of two arrays: the first array is the elements for which block is true, the second array is the elements for which block is false or nil.

Returns Array<Array<Object>] an array of two arrays: the first array is the elements for which block is true, the second array is the elements for which block is false or nil.

Examples:

enum.bisect {|obj| block}
=> array of positives, array of negatives

Returns:

  • (Array<Array<Object>] an array of two arrays: the first array is the elements for which block is true, the second array is the elements for which block is false or nil.)

    Array<Array<Object>] an array of two arrays: the first array is the elements for which block is true, the second array is the elements for which block is false or nil.



286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/webget_ruby_ramp/enumerable.rb', line 286

def bisect
  accept=[]
  reject=[]
  each{|item| 
   if yield(item)
    accept << item
   else
    reject << item
   end
  }
  return accept,reject
end

#cartesian_product(*enums) ⇒ Object



421
422
423
# File 'lib/webget_ruby_ramp/enumerable.rb', line 421

def cartesian_product(*enums)
  Enumerable.cartesian_product(self,*enums)
end

#hash_byHash<Object,Object>

Convert the enumerable to a hash by mapping each item to a pair [item, new item]

Examples:

strings = ["red","blue","green"]
strings.hash_by{|a| [a.size, a.upcase]}
=> {3 => "RED", 4 => "BLUE", 5 => "GREEN"}

Returns:

See Also:



80
81
82
# File 'lib/webget_ruby_ramp/enumerable.rb', line 80

def hash_by
  map{|item| yield(item)}.to_h
end

#index_byHash<Integer,Object>

Convert the enumerable to a hash by mapping each item to a pair [index ,item]

Rails has this method.

From stackoverflow.com/questions/412771/cleanest-way-to-create-a-hash-from-an-array

Examples:

strings = ["red","blue","green"]
strings.index_by{|a| a.size]}
=> {3 => "red", 4 => "blue", 5 => "green"}

Returns:

See Also:



64
65
66
# File 'lib/webget_ruby_ramp/enumerable.rb', line 64

def index_by
  inject({}) {|hash, elem| hash.merge!(yield(elem) => elem) }
end

#intersect?(enum) ⇒ Boolean

This implementation uses #to_a and array intersection. A developer may want to optimize this implementation for other classes, such as detecting whether a range intersects another range simply by comparing the ranges’ min/max values.

Examples:

['a','b','c'].intersect?(['c','d','e'] => true
['a','b','c'].intersect?(['d','e','f'] => false

Returns:

  • (Boolean)

    true if this enum intersects another enum.



387
388
389
# File 'lib/webget_ruby_ramp/enumerable.rb', line 387

def intersect?(enum)
  return ((self===enum and self.to_a.size>0) or ((self.to_a & enum.to_a).size>0))
end

#join(*op) ⇒ String

Shortcut to Array#join to concatenate the items into a string

Examples:

["foo", "goo", "hoo"].join
=> "foogoohoo"

Returns:

  • (String)

    concatenated string

See Also:



364
365
366
# File 'lib/webget_ruby_ramp/enumerable.rb', line 364

def join(*op)
 to_a.join(*op)
end

#map_idEnumerable<Object>

Map each item => item.id

A typical use is to convert a list of ActiveRecord items to a list of id items.

This method is a fast way to get the same results as items.map(&:id)

Examples:

users = User.find(:all)
users.map_id => [1,2,3,4,...]

Returns:



105
106
107
# File 'lib/webget_ruby_ramp/enumerable.rb', line 105

def map_id
  map{|item| item.id}
end

#map_to_aEnumberable<Array<Object>>

Map each item => item.to_a

A typical use is to convert a list with Set items to a list of Array items, so you can more easily iterate over the the Array items.

See www.ruby-doc.org/core/classes/Enumerable.html#M003148

Examples:

set1 = Set.new([:a,:b,:c])
set2 = Set.new([:d,:e,:f])
set3 = Set.new([:g,:h,:i])
sets = [set1, set2, set3]
sets.map_to_a => [[:a, :b, :c], [:d, :e, :f], [:g, :h, :i]]

Returns:

  • (Enumberable<Array<Object>>)

    a list of each item.to_a



126
127
128
# File 'lib/webget_ruby_ramp/enumerable.rb', line 126

def map_to_a
  map{|item| [item]}
end

#map_to_fEnumerable<Float>

Map each item => item.to_f

A typical use is to convert a list of String items to a list of float items.

This method is a fast way to get the same results as items.map(&:to_f)

Examples:

strings = ["1","2","3"]
strings.map_to_f => [1.0, 2.0, 3.0]

Returns:

  • (Enumerable<Float>)

    a list of each item.to_f



143
144
145
# File 'lib/webget_ruby_ramp/enumerable.rb', line 143

def map_to_f
  map{|item| item.to_f}
end

#map_to_iEnumerable<Integer>

Map each item => item.to_i

A typical use is to convert a list of String items to a list of integer items.

This method is a fast way to get the same results as items.map(&:to_i)

Examples:

strings = ["1","2","3"]
strings.map_to_i => [1, 2, 3]  

Returns:



160
161
162
# File 'lib/webget_ruby_ramp/enumerable.rb', line 160

def map_to_i
  map{|item| item.to_i}
end

#map_to_sEnumerable<String>

Map each item => item.to_s

A typical use is to convert a list of Numeric items to a list of String items.

This method is a fast way to get the same results as items.map(&:to_s)

Examples:

numbers = [1, 2, 3]
numbers.map_to_s => ["1", "2", "3"]  

Returns:



177
178
179
# File 'lib/webget_ruby_ramp/enumerable.rb', line 177

def map_to_s
  map{|item| item.to_s}
end

#map_to_symEnumerable<Symbol>

Map each item => item.to_sym

A typical use is to convert a list of Object items to a list of Symbol items.

This method is a fast way to get the same results as items.map(&:to_sym)

Examples:

strings = ["foo", "goo", "hoo"]
strings.map_to_sym => [:foo, :goo, :hoo]

Returns:



194
195
196
# File 'lib/webget_ruby_ramp/enumerable.rb', line 194

def map_to_sym
  map{|item| item.to_sym}
end

#map_with_indexEnumerable<Object>

Map each item and its index => a new output

Examples:

strings = ["a", "b", "c"]
strings.map_with_index{|string,index| "#{string}#{index}"}
 => ["a0, "b1", "c3"]

Returns:

See Also:

  • #map
  • #each_with_index


210
211
212
213
# File 'lib/webget_ruby_ramp/enumerable.rb', line 210

def map_with_index
  index=-1
  map{|item| index+=1; yield(item,index)}
end

#nitems_untilInteger

Returns the number of leading elements for which block is false.

Examples:

enum.nitems_until {| obj | block }
=> number of items

Returns:

  • (Integer)

    the number of leading elements for which block is false.



326
327
328
329
330
331
332
333
334
335
336
# File 'lib/webget_ruby_ramp/enumerable.rb', line 326

def nitems_until
  num = 0
  each{|item|
    if yield(item) 
      break
    else
      num+=1
    end
  }
  return num
end

#nitems_whileInteger

Returns the number of leading elements for which block is not false or nil.

Examples:

enum.nitems_while {| obj | block }
 => number of items

Returns:

  • (Integer)

    the number of leading elements for which block is not false or nil.



313
314
315
316
317
# File 'lib/webget_ruby_ramp/enumerable.rb', line 313

def nitems_while
  num = 0
  each{|item| yield(item) ? (num+=1) : break}
  return num
end

#nitems_with_indexInteger

Calls block with two arguments, the item and its index, for each item in enum.

Examples:

enum.nitems_with_index {|obj,i| block }
 => number of items

Returns:

  • (Integer)

    the number of leading elements for which block is true.



347
348
349
350
351
# File 'lib/webget_ruby_ramp/enumerable.rb', line 347

def nitems_with_index
  index = 0
  each{|item| yield(item,index) ? (index+=1) : break}
  return index
end

#power_setArray<Array<Object>>

Calculate the power set.

This implementation is from the blog post below:

Examples:

[1,2,3].power_set.sort
=>  [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]

Returns:

  • (Array<Array<Object>>)

    the power set: an array with all subsets of the enum’s elements.

See Also:



438
439
440
# File 'lib/webget_ruby_ramp/enumerable.rb', line 438

def power_set
  inject([[]]){|c,y|r=[];c.each{|i|r<<i;r<<i+[y]};r}
end

#select_untilArray<Object>

Returns the leading elements for which block is false or nil.

Examples:

enum.select_until {|obj| block }
 => array

Returns:

  • (Array<Object>)

    the leading elements for which block is false or nil.



242
243
244
245
246
# File 'lib/webget_ruby_ramp/enumerable.rb', line 242

def select_until
  arr = []
  each{|item| yield(item) ? break : (arr << item)}
  return arr
end

#select_whileArray<Object>

Returns the leading elements for which block is not false or nil.

Examples:

enum.select_while {|obj| block }
 => array

Returns:

  • (Array<Object>)

    the leading elements for which block is not false or nil.



229
230
231
232
233
# File 'lib/webget_ruby_ramp/enumerable.rb', line 229

def select_while
  arr = []
  each{|item| yield(item) ? (arr << item) : break}
  return arr
end

#select_with_indexArray<Object> the leading elements for which block is not false or nil.

Calls block with two arguments, the item and its index, for each item in enum.

Examples:

enum.select_with_index {|obj,i| block } 
=> array

Returns:

  • (Array<Object> the leading elements for which block is not false or nil.)

    Array<Object> the leading elements for which block is not false or nil.



257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/webget_ruby_ramp/enumerable.rb', line 257

def select_with_index
  index = 0
  arr = []
  each{|item| 
    if yield(item,index)
      arr << item
      index+=1
    else
      break
    end
  }
  return arr
end

#to_hHash<Object,Object>

Convert an enumerable to a hash.

If a key occurs more than once, then this will automatically convert the value to an array of the keys’ values.

Examples:

array=[[:a, :b],[:c, :d],[:e, :f]]
array.to_h => {:a=>:b, :c=>:d, :e=>:f}
array=[[:a,:b],[:a,:c],[:a,:d]]
array.to_h => {:a=>[:b, :c, :d]}

Returns:



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/webget_ruby_ramp/enumerable.rb', line 29

def to_h
  hash={}
  dupe={}
  each{|key,val|
    if hash.key? key
      if dupe.key? key
        hash[key] << val
      else
        hash[key]=[hash[key]]
        hash[key] << val
        dupe[key]=true
      end
    else
      hash[key]=val
    end
  }
  return hash
end