Class: Array

Inherits:
Object show all
Defined in:
lib/webget_ruby_ramp/array.rb

Overview

Array extensions

Instance Method Summary collapse

Instance Method Details

#choiceObject

Implemented in Ruby 1.9

Examples:

[1,2,3,4].choice => 2
[1,2,3,4].choice => 4
[1,2,3,4].choice => 3

Returns:

  • (Object)

    a random item from the array



90
91
92
# File 'lib/webget_ruby_ramp/array.rb', line 90

def choice
  self[Kernel.rand(size)]
end

#choices(count) ⇒ Array

Returns a new array filled with count calls to choice.

Examples:

[1,2,3,4].choices(2) => [3,1]
[1,2,3,4].choices(3) => [4,2,3]

Returns:

  • (Array)

    a new array filled with count calls to choice



101
102
103
104
105
# File 'lib/webget_ruby_ramp/array.rb', line 101

def choices(count)
  arr = Array.new
  count.times { arr << self.choice }
  return arr
end

#divvy(number_of_slices) ⇒ Array<Array<Object>>

Divvy the array, like a pie, into n number of slices.

If the array divides evenly, then each slice has size/n items.

Otherwise, divvy makes a best attempt by rounding up to give earlier slices one more item, which makes the last slice smaller:

If the array size so small compared to n that there is no mathematical way to n slices, then divvy will return as many slices as it can.

Examples:

[1,2,3,4,5].divvy(2) => [[1,2,3],[4,5]]
[1,2,3,4,5,6,7].divvy(3) => [[1,2,3],[4,5,6],[7]]
[1,2,3,4,5,6].divvy(4) => [[1,2],[3,4],[5,6]]

Returns:



178
179
180
181
182
# File 'lib/webget_ruby_ramp/array.rb', line 178

def divvy(number_of_slices)
  (number_of_slices.is_a? Integer) or (raise ArgumentError, "number_of_slices must be an integer")
  (number_of_slices > 0) or (raise ArgumentError, "number_of_slices must be > 0")
  return slices((length.to_f/number_of_slices.to_f).ceil)
end

#intersectArray

In typical usage, each item is an array.

Examples:

arr=[[1,2,3,4],[3,4,5,6]]
arr.intersect
=> [3,4]

with proc

arr.map(&:foo).intersect
=> foos that are in all of the array items

with nil

[].intersect => []

Returns:

  • (Array)

    the intersection of the array’s items.



228
229
230
# File 'lib/webget_ruby_ramp/array.rb', line 228

def intersect
  inject{|inj,item| inj & item.to_a } || []
end

#join(*fixes) ⇒ String

Concatenate the items into a string by join.

Examples:

Typical Array#join with infix

list=['a','b','c']
list.join("*") => "a*b*c"

Improved join with infix, prefix, suffix

list=['a','b','c']
list.join("*","[","]") => "[a]*[b]*[c]"

Improved join with just prefix and suffix

list=['a','b','c']
list.join("[","]") => "[a][b][c]"

Returns:

  • (String)

    concatenated string



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/webget_ruby_ramp/array.rb', line 31

def join(*fixes)
  if fixes.is_a?(String) then return self.ruby_join(fixes) end
  case fixes.size
  when 0
    return self.ruby_join()
  when 1
    return self.ruby_join(fixes[0])
  when 2
    prefix=fixes[0].to_s
    suffix=fixes[1].to_s
    return self.map{|item| prefix + item.to_s + suffix}.ruby_join()
  when 3
    infix =fixes[0].to_s
    prefix=fixes[1].to_s
    suffix=fixes[2].to_s
    return self.map{|item| prefix + item.to_s + suffix}.ruby_join(infix)
  else
    raise ArgumentError, "join() takes 0-3 arguments; you gave #{fixes.size}]"
  end
end

#onto(values) ⇒ Hash

This is identical to calling foo.zip(values).to_h

Examples:

foo=[:a,:b,:c]
goo=[:x,:y,:z]
foo.onto(goo) => {:a=>:x, :b=>:y, :c=>:z}

Returns:

  • (Hash)

    a hash of this array’s items as keys, mapped onto another array’s items as values.



118
119
120
121
# File 'lib/webget_ruby_ramp/array.rb', line 118

def onto(values)
  size==values.size or raise ArgumentError, "Array size #{size} must match values size #{size}" 
  zip(values).to_h
end

#rotate!Array

Move the first item to the last by using Array#shift and Array#push

Examples:

[1,2,3,4].rotate! => [2,3,4,1]
['a','b','c'].rotate! => ['b','c','a']
[].rotate! => []

Returns:



73
74
75
76
77
78
# File 'lib/webget_ruby_ramp/array.rb', line 73

def rotate!
  if size>0
    push item=shift
  end
  self
end

#ruby_joinObject

Alias join because we’re going to override it



12
# File 'lib/webget_ruby_ramp/array.rb', line 12

alias :ruby_join :join

#shifted(number_of_items = 1) ⇒ Array Also known as: cdr, rest

Ruby programmers may prefer this alias wording:

list.first => 'a'
list.rest => ['b','c']

LISP programmers may prefer this alias wording:

list.car => 'a'
list.cdr => ['b','c']

Examples:

list=['a','b','c']
list.shift => 'a'
list.shifted => ['b','c']

with length

list.shifted(0) => ['a','b','c']
list.shifted(1) => ['b','c']
list.shifted(2) => ['c']
list.shifted(3) => []

Returns:

  • (Array)

    the rest of the items of self, after a shift.



262
263
264
265
266
# File 'lib/webget_ruby_ramp/array.rb', line 262

def shifted(number_of_items=1)
  (number_of_items.is_a? Integer) or (raise ArgumentError, "number_of_items must be an integer")
  (number_of_items >= 0) or (raise ArgumentError, "number_of_items must be >= 0")
  slice(number_of_items,self.length-number_of_items)
end

#shifted!(number_of_items = 1) ⇒ Array Also known as: cdr!, rest!

Delete the first number_of_items items.

If n is greater than the array size, then return []

Examples:

list=['a','b','c']
list.shifted!
list => ['b','c']

with length:

list=['a','b','c']
list.shifted!(2)
list => ['c']

Returns:

  • (Array)

    the array, minus the deleted items.



289
290
291
292
293
294
# File 'lib/webget_ruby_ramp/array.rb', line 289

def shifted!(number_of_items=1)
  (number_of_items.is_a? Integer) or (raise ArgumentError, "number_of_items must be an integer")
  (number_of_items >= 0) or (raise ArgumentError, "number_of_items must be >= 0")
  slice!(0,number_of_items)
  return self
end

#shuffleArray

This implementation is optimized for speed, not for memory use. See codeidol.com/other/rubyckbk/Arrays/Shuffling-an-Array/

Examples:

list=
list=['a','b','c']
list.shuffle!
list => ['c','a','b']

Returns:

  • (Array)

    a new array with the items shuffled.



332
333
334
# File 'lib/webget_ruby_ramp/array.rb', line 332

def shuffle  
  dup.shuffle!  
end

#shuffle!Array

Randomly arrange the array items.

This implementation is optimized for speed, not for memory use. See codeidol.com/other/rubyckbk/Arrays/Shuffling-an-Array/

Examples:

list=
list=['a','b','c']
list.shuffle!
list => ['c','a','b']

Returns:

  • (Array)

    the array, with its items shuffled.



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

def shuffle!  
  each_index do |i| 
    j = rand(length-i) + i
    self[j], self[i] = self[i], self[j]  
  end
end

#size?Boolean

Returns true if size > 0.

Examples:

[1,2,3].size? => true
[].size? => false

Returns:

  • (Boolean)

    true if size > 0



59
60
61
# File 'lib/webget_ruby_ramp/array.rb', line 59

def size?
  return size>0
end

#slices(slice_length) ⇒ Array<Array<Object>>

Slice the array.

If the slices don’t divide evenly, then the last is smaller.

Examples:

[1,2,3,4,5,6,7,8].slices(2) => [[1,2],[3,4],[5,6],[7,8]]
[1,2,3,4,5,6,7,8].slices(4) => [[1,2,3,4],[5,6,7,8]]
[1,2,3,4,5,6,7,8].slices(3) => [[1,2,3],[4,5,6],[7,8]] 
[1,2,3,4,5,6,7,8].slices(5) => [[1,2,3,4,5],[6,7,8]] 

Returns:



145
146
147
148
149
150
151
152
153
154
155
# File 'lib/webget_ruby_ramp/array.rb', line 145

def slices(slice_length)
  (slice_length.is_a? Integer) or (raise ArgumentError, "slice_length must be an integer")
  (slice_length > 0) or (raise ArgumentError, "slice_length must be > 0")
  arr=[]
  index=0
  while index<length
    arr.push self[index...(index+slice_length)]
    index+=slice_length
  end
  return arr
end

#to_csv(ops = {}) ⇒ String

N.b. this method uses the multi-dimensional if the array’s first item is also an array.

Examples:

of a one-dimensional array


[1,2,3].to_csv => "1,2,3\n"

of a multi-dimensional array


[[1,2,3],[4,5,6]] => "1,2,3\n4,5,6\n"

of a blank array


[].to_csv => ""

Returns:

  • (String)

    a CSV (Comma Separated Value) string of this array.



360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/webget_ruby_ramp/array.rb', line 360

def to_csv(ops={})

  return "" if size==0

  generator = RUBY_VERSION >= "1.9" ? CSV : CSV::Writer

  str=''
  if size>0 and self[0].is_a?Array
    generator.generate(str) do |csv|
      self.each do |row|
        csv << row
      end
    end
  else
    generator.generate(str) do |csv|
      csv << self.map{|item| item.to_s}
    end
  end
  return str
end

#to_tsv(ops = {}) ⇒ String Also known as: to_tdf

Each subarray becomes one ‘line’ in the output.

Examples:

of a blank array


[].to_csv => ""

Returns:

  • (String)

    a TSV (Tab Separated Value) string representation of a multi-dimensional array.



391
392
393
# File 'lib/webget_ruby_ramp/array.rb', line 391

def to_tsv(ops={})
  self.map{|row| row.join("\t")+"\n"}.join
end

#unionArray

In typical use, each item is an array.

Examples:

using Ruby Array pipe

arr=[[1,2,3,4],[3,4,5,6]]
arr.union => [1,2,3,4,5,6]

with proc

arr.map(&:foo).union
=> foos that are in any of the array items

with nil

[].union => []

Returns:

  • (Array)

    the union of the array’s items.



207
208
209
# File 'lib/webget_ruby_ramp/array.rb', line 207

def union
  inject{|inj,item| inj | item.to_a } || []
end