Module: DaruLite::ArrayHelper
- Defined in:
- lib/daru_lite/helpers/array.rb
Class Method Summary collapse
- .array_of?(array, match) ⇒ Boolean
-
.recode_repeated(array) ⇒ Object
Recode repeated values on an array, adding the number of repetition at the end Example: a=%wb c c d d d e a.recode_repeated => [“a”,“b”,“c_1”,“c_2”,“d_1”,“d_2”,“d_3”,“e”].
- .sort_composite_data(array) ⇒ Object
Class Method Details
.array_of?(array, match) ⇒ Boolean
34 35 36 37 38 |
# File 'lib/daru_lite/helpers/array.rb', line 34 def array_of?(array, match) array.is_a?(Array) && !array.empty? && array.all? { |el| match === el } # rubocop:disable Style/CaseEquality,Performance/RedundantEqualityComparisonBlock end |
.recode_repeated(array) ⇒ Object
Recode repeated values on an array, adding the number of repetition at the end Example:
a=%w{a b c c d d d e}
a.recode_repeated
=> ["a","b","c_1","c_2","d_1","d_2","d_3","e"]
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/daru_lite/helpers/array.rb', line 11 def recode_repeated(array) return array if array.size == array.uniq.size # create hash of { <name> => 0} # for all names which are more than one time in array counter = array .group_by(&:itself) .select { |_, g| g.size > 1 } .keys .to_h { |n| [n, 0] } # ...and use this hash for actual recode array.collect do |n| if counter.key?(n) counter[n] += 1 new_n = format('%<index>s_%<counter>d', index: n, counter: counter[n]) n.is_a?(Symbol) ? new_n.to_sym : new_n else n end end end |
.sort_composite_data(array) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/daru_lite/helpers/array.rb', line 40 def sort_composite_data(array) array.sort rescue ArgumentError, TypeError => e case e.to_s when /comparison of Symbol with String failed/, /comparison of Symbol with \d+ failed/, /comparison of String with :.* failed/, /comparison of Integer with :.* failed/, /no implicit conversion from nil to integer/ array.sort_by(&:to_s) end end |