Module: Darthjee::CoreExt::Array
- Included in:
- Array
- Defined in:
- lib/darthjee/core_ext/array.rb,
lib/darthjee/core_ext/array/hash_builder.rb
Overview
Module containing new usefull methods to Ruby vanilla Array
Defined Under Namespace
Classes: HashBuilder
Instance Method Summary collapse
-
#as_hash(keys) ⇒ ::Hash
Returns a Hash where the values are the elements of the array.
-
#average ⇒ ::Float
Calculate the average of all values in the array.
-
#chain_map(*methods) {|element| ... } ⇒ ::Array
Maps the array using the given methods on each element of the array.
-
#mapk(*keys) ⇒ ::Array
Maps array chain fetching the keys of the hashes inside.
-
#procedural_join(mapper = proc(&:to_s)) {|previous, nexte| ... } ⇒ String
Joins elements in a string using a proc.
-
#random ⇒ Object
Reeturns a random element of the array without altering it.
-
#random! ⇒ Object
Reeturns a random element of the array removing it from the array.
Instance Method Details
#as_hash(keys) ⇒ ::Hash
Returns a Hash where the values are the elements of the array
22 23 24 |
# File 'lib/darthjee/core_ext/array.rb', line 22 def as_hash(keys) Array::HashBuilder.new(self, keys).build end |
#average ⇒ ::Float
Calculate the average of all values in the array
36 37 38 39 40 |
# File 'lib/darthjee/core_ext/array.rb', line 36 def average return 0 if empty? sum * 1.0 / length end |
#chain_map(*methods) {|element| ... } ⇒ ::Array
Maps the array using the given methods on each element of the array
64 65 66 67 68 69 70 71 72 |
# File 'lib/darthjee/core_ext/array.rb', line 64 def chain_map(*methods, &) result = methods.inject(self) do |array, method| array.map(&method) end return result unless block_given? result.map(&) end |
#mapk(*keys) ⇒ ::Array
Maps array chain fetching the keys of the hashes inside
fetched from hashes inside
96 97 98 99 100 101 102 |
# File 'lib/darthjee/core_ext/array.rb', line 96 def mapk(*keys) keys.inject(self) do |enum, key| enum.map do |hash| hash&.[] key end end end |
#procedural_join(mapper = proc(&:to_s)) {|previous, nexte| ... } ⇒ String
Joins elements in a string using a proc
Uses the proc given elements to Strig and a block for determinating the joining string
to string before joining
130 131 132 133 134 135 136 137 138 139 140 |
# File 'lib/darthjee/core_ext/array.rb', line 130 def procedural_join(mapper = proc(&:to_s)) return '' if empty? map = map_to_hash(&mapper) map.inject do |(previous, string), (nexte, nexte_string)| link = yield(previous, nexte) if block_given? [nexte, "#{string}#{link}#{nexte_string}"] end.last.to_s end |
#random ⇒ Object
Reeturns a random element of the array without altering it
150 151 152 |
# File 'lib/darthjee/core_ext/array.rb', line 150 def random self[Random.rand(size)] end |
#random! ⇒ Object
Reeturns a random element of the array removing it from the array
162 163 164 |
# File 'lib/darthjee/core_ext/array.rb', line 162 def random! slice!(Random.rand(size)) end |