Module: Enumerable

Defined in:
lib/webget_ramp/enumerable.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.cartesian_product(*enums) ⇒ Object

Return the cartesian product of the enumerations. en.wikipedia.org/wiki/Cartesian_product

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

By Thomas Hafner See www.ruby-forum.com/topic/95519

For our benchmarks, we also compared thesk:



352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/webget_ramp/enumerable.rb', line 352

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

#bisectObject

enum.bisect {|obj| block} => array of positives, array of negatives Returns two arrays: the first contains the elements for which block is true, the second contains the elements for which block is false or nil.



250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/webget_ramp/enumerable.rb', line 250

def bisect
  a=[]
  b=[]
  each{|x| 
   if yield(x)
    a << x
   else
    b << x
   end
  }
  return a,b
end

#cartesian_product(*enums) ⇒ Object



366
367
368
# File 'lib/webget_ramp/enumerable.rb', line 366

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

#hash_byObject

Convert the enumerable to a hash by mapping each item to a key,value pair.

Example

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

Compare #index_by



71
72
73
# File 'lib/webget_ramp/enumerable.rb', line 71

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

#index_byObject

Convert the enumerable to a hash by mapping each item to a key,item pair.

Example

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

Rails has this method.

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

Compare #hash_by



57
58
59
# File 'lib/webget_ramp/enumerable.rb', line 57

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

#intersect?(enum) ⇒ Boolean

Returns true if this enum intersects another enum.

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)


334
335
336
# File 'lib/webget_ramp/enumerable.rb', line 334

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

#join(prefix = nil, suffix = nil) ⇒ Object

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



311
312
313
# File 'lib/webget_ramp/enumerable.rb', line 311

def join(prefix=nil,suffix=nil)
 to_a.join(prefix,suffix)
end

#map_idObject

Map each item => item.id

Example

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

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)



94
95
96
# File 'lib/webget_ramp/enumerable.rb', line 94

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

#map_to_aObject

Map each item => item.to_a

Example

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]]

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



113
114
115
# File 'lib/webget_ramp/enumerable.rb', line 113

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

#map_to_fObject

Map each item => item.to_f

Example

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

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)



128
129
130
# File 'lib/webget_ramp/enumerable.rb', line 128

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

#map_to_iObject

Map each item => item.to_i

Example

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

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)



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

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

#map_to_sObject

Map each item => item.to_s

Example

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

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)



158
159
160
# File 'lib/webget_ramp/enumerable.rb', line 158

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

#map_to_symObject

Map each item => item.to_sym

Example

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

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)



173
174
175
# File 'lib/webget_ramp/enumerable.rb', line 173

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

#map_with_indexObject

Map each item and its index => a new output

cf. Enumerable#map, Enumerable#each_with_index

Example

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


188
189
190
191
# File 'lib/webget_ramp/enumerable.rb', line 188

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

#nitems_untilObject

enum.nitems_until {| obj | block } => number of items Returns the number of leading elements for which block is false.



284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/webget_ramp/enumerable.rb', line 284

def nitems_until
  n = 0
  each{|x|
    if yield(x) 
      break
    else
      n+=1
    end
  }
  return n
  irb
end

#nitems_whileObject

enum.nitems_while {| obj | block } => number of items Returns the number of leading elements for which block is not false or nil.



274
275
276
277
278
# File 'lib/webget_ramp/enumerable.rb', line 274

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

#nitems_with_indexObject

enum.nitems_with_index {|obj,i| block } => number of items Calls block with two arguments, the item and its index, for each item in enum. Returns the number of leading elements for which block is true.



302
303
304
305
306
# File 'lib/webget_ramp/enumerable.rb', line 302

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

#power_setObject

Return the power set: an array with all subsets of the enum’s elements. en.wikipedia.org/wiki/Power_set

This implementation is from johncarrino.net/blog/2006/08/11/powerset-in-ruby/

Example

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


381
382
383
# File 'lib/webget_ramp/enumerable.rb', line 381

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

#select_untilObject

enum.select_until {|obj| block } => array Returns an array containing the leading elements for which block is false or nil.



214
215
216
217
218
# File 'lib/webget_ramp/enumerable.rb', line 214

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

#select_whileObject

enum.select_while {|obj| block } => array Returns an array containing the leading elements for which block is not false or nil.



204
205
206
207
208
# File 'lib/webget_ramp/enumerable.rb', line 204

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

#select_with_indexObject

enum.select_with_index {|obj,i| block } => array Calls block with two arguments, the item and its index, for each item in enum. Returns an array containing the leading elements for which block is not false or nil.



225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/webget_ramp/enumerable.rb', line 225

def select_with_index
  i = 0
  a = []
  each{|x| 
    if yield(x,i)
      a << x
      i+=1
    else
      break
    end
  }
  return a
end

#to_hObject

Convert an enumerable to a hash.

Example

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

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

Example

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


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/webget_ramp/enumerable.rb', line 24

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