Class: Array

Inherits:
Object show all
Defined in:
lib/smklib/array_ext.rb

Instance Method Summary collapse

Instance Method Details

#create_nested_array(keys) ⇒ Object

takes an array of hashes and an array of ordered hash keys creates a nested array based on the elements of the hashes name the last elt in the key array ‘count’ if you want to pair the last two elements



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/smklib/array_ext.rb', line 20

def create_nested_array(keys)
  h_count      = self[0].length   # count the number of elements in the hash - assumes all are the same length
  old_vals     = Hash.new        # keep a record of elements already recorded
  o            = Array.new       # create output variable 
  str,str_eval = nil             # create temp variable for holding code to execute
  has_count_column = keys.last == 'count'
  h_end        = (has_count_column) ? h_count - 2 : h_count - 1
  
  self.each do |a|
    current = o
    keys.each_with_index do |k,i|
		begin
			unless (i >= h_end and has_count_column)
			#if ((i != h_end) || (keys.last != 'count'))
				if a[k] != old_vals[k]
					current << [ a[k], [] ]
					keys[i+1..keys.length].each { |q| old_vals[q] = nil }
				end
				current = current.last.last # reference the value array
			else 
				current << [a[k], a['count']] if (i == h_end)
			end
			old_vals[k] = a[k]  # record element we just looked at
		rescue Exception => e
			raise "Error: #{e.inspect}, " +
			      "current = #{current.inspect}, " +
			      "a[k] = #{a[k].inspect} and a[k] != old_vals[k] = #{(a[k] != old_vals[k]).inspect}, " +
			      "a = #{a.inspect}, " +
			      "o = #{o.to_yaml}, " +
			      "self = #{self.to_yaml}, "
		end
    end
  end
  o
end

#multi_slice(*slice_size) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/smklib/array_ext.rb', line 3

def multi_slice(*slice_size)
	return self if slice_size.empty?
	tmp_out = []
	index = 0
	n = 0
	while(index < size)
		ss = slice_size[n] || slice_size.first
		tmp_out << slice(index, ss)
		index += ss
		n += 1
	end
	tmp_out
end

#randomizeObject



56
57
58
# File 'lib/smklib/array_ext.rb', line 56

def randomize
  self.sort { |l,r| rand(2) - 1  }
end

#randomize!Object



60
61
62
# File 'lib/smklib/array_ext.rb', line 60

def randomize!
  self.sort! { |l,r| rand(2) - 1  }
end

#to_double_arrayObject



64
65
66
67
# File 'lib/smklib/array_ext.rb', line 64

def to_double_array
	self.each_with_index { |x,i| self[i] = [x,x] }
	self
end