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) ⇒ 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:



354
355
356
357
358
359
360
361
362
363
364
365
366
# File 'lib/webget_ruby_ramp/enumerable.rb', line 354

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.



253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/webget_ruby_ramp/enumerable.rb', line 253

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

#cartesian_product(*enums) ⇒ Object



368
369
370
# File 'lib/webget_ruby_ramp/enumerable.rb', line 368

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.upcase]}
=> {3 => "RED", 4 => "BLUE", 5 => "GREEN"}

Compare #index_by



74
75
76
# File 'lib/webget_ruby_ramp/enumerable.rb', line 74

def hash_by
  map{|item| yield(item)}.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



60
61
62
# File 'lib/webget_ruby_ramp/enumerable.rb', line 60

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)


336
337
338
# File 'lib/webget_ruby_ramp/enumerable.rb', line 336

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

#join(*op) ⇒ Object

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



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

def join(*op)
 to_a.join(*op)
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)



97
98
99
# File 'lib/webget_ruby_ramp/enumerable.rb', line 97

def map_id
  map{|item| item.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



116
117
118
# File 'lib/webget_ruby_ramp/enumerable.rb', line 116

def map_to_a
  map{|item| [item]}
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)



131
132
133
# File 'lib/webget_ruby_ramp/enumerable.rb', line 131

def map_to_f
  map{|item| item.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)



146
147
148
# File 'lib/webget_ruby_ramp/enumerable.rb', line 146

def map_to_i
  map{|item| item.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)



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

def map_to_s
  map{|item| item.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)



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

def map_to_sym
  map{|item| item.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"]


191
192
193
194
# File 'lib/webget_ruby_ramp/enumerable.rb', line 191

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

#nitems_untilObject

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



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

def nitems_until
  num = 0
  each{|item|
    if yield(item) 
      break
    else
      num+=1
    end
  }
  return num
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.



277
278
279
280
281
# File 'lib/webget_ruby_ramp/enumerable.rb', line 277

def nitems_while
  num = 0
  each{|item| yield(item) ? (num+=1) : break}
  return num
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.



304
305
306
307
308
# File 'lib/webget_ruby_ramp/enumerable.rb', line 304

def nitems_with_index
  index = 0
  each{|item| yield(item,index) ? (index+=1) : break}
  return index
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]]


383
384
385
# File 'lib/webget_ruby_ramp/enumerable.rb', line 383

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.



217
218
219
220
221
# File 'lib/webget_ruby_ramp/enumerable.rb', line 217

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

#select_whileObject

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



207
208
209
210
211
# File 'lib/webget_ruby_ramp/enumerable.rb', line 207

def select_while
  arr = []
  each{|item| yield(item) ? (arr << item) : break}
  return arr
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.



228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/webget_ruby_ramp/enumerable.rb', line 228

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


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

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