Class: Array
Instance Method Summary collapse
-
#avg ⇒ Object
(also: #average)
Return the average of numbers within the array.
-
#chunk(n, pad_with = nil, &block) ⇒ Object
(also: #in_groups_of)
Split an array into chunks of length
n
. -
#from(index) ⇒ Object
Return array of elements after index.
-
#pad(n, pad_with = nil) ⇒ Object
Pad array with expected length
n
, andpad_with
an optional object or nil. -
#sum ⇒ Object
Return the sum of numbers within the array.
-
#to(index) ⇒ Object
Return array of elements up to index.
Instance Method Details
#avg ⇒ Object Also known as: average
Return the average of numbers within the array.
16 17 18 19 |
# File 'lib/rext/array/helpers.rb', line 16 def avg return 0 if empty? sum.to_f / length end |
#chunk(n, pad_with = nil, &block) ⇒ Object Also known as: in_groups_of
Split an array into chunks of length n
. Optionally you may pad_with
an object to retain a uniform length per chunk.
Examples
[1,2,3].chunk(2) # => [[1,2], [3, nil]]
[1,2,3].chunk(2, 'x') # => [[1,2], [3, 'x']]
[1,2,3].chunk(2, false) # => [[1,2], [3]]
[1,2,3].in_groups_of(2) do |chunk|
# Do something
end
See
-
Array#pad
69 70 71 72 73 74 75 76 77 |
# File 'lib/rext/array/helpers.rb', line 69 def chunk n, pad_with = nil, &block returning [] do |chunks| each_slice n do |chunk| chunk.pad n, pad_with unless pad_with == false yield chunk if block chunks << chunk end end end |
#from(index) ⇒ Object
Return array of elements after index.
25 26 27 |
# File 'lib/rext/array/helpers.rb', line 25 def from index self[index..-1] end |
#pad(n, pad_with = nil) ⇒ Object
Pad array with expected length n
, and pad_with
an optional object or nil.
Examples
[1,2].pad(4) # => [1,2,nil,nil]
[1,2].pad(4) # => [1,2,'x','x']
[1,2].pad(2) # => [1,2]
47 48 49 |
# File 'lib/rext/array/helpers.rb', line 47 def pad n, pad_with = nil fill pad_with, length, n - length end |
#sum ⇒ Object
Return the sum of numbers within the array.
9 10 11 |
# File 'lib/rext/array/helpers.rb', line 9 def sum inject(0) { |sum, n| sum += n } end |
#to(index) ⇒ Object
Return array of elements up to index.
32 33 34 |
# File 'lib/rext/array/helpers.rb', line 32 def to index self[0..index] end |