Module: ArrayHelper
- Included in:
- Array
- Defined in:
- lib/rubyhelper/arrayhelper.rb
Instance Method Summary collapse
- #average ⇒ Object
- #averagef ⇒ Object
-
#maxs(n = 1) ⇒ Object
TODO benchmark with sort{|e| -e}.
- #sum ⇒ Object
- #sumf ⇒ Object
-
#to_clean_s(sep = ' ') ⇒ Object
A simple function like to_s(), but return a clean String for exemple : [1,2,3].to_clean_s(“ ; ”) => “1 ; 2 ; 3” ==Parameters: sep: A String to separe each element (or an Array, see to_clean_s_with_array).
-
#to_clean_s_with_array(sep) ⇒ Object
You can use an array as separator : [“,”, “ ”] will successively ‘,’ and ‘ ’.
- #to_clean_s_with_string(sep) ⇒ Object
Instance Method Details
#average ⇒ Object
42 43 44 |
# File 'lib/rubyhelper/arrayhelper.rb', line 42 def average return (self.size > 0) ? (self.sum / self.size) : (0) end |
#averagef ⇒ Object
46 47 48 |
# File 'lib/rubyhelper/arrayhelper.rb', line 46 def averagef return (self.size > 0) ? (self.sumf / self.size.to_f) : (0.0) end |
#maxs(n = 1) ⇒ Object
TODO benchmark with sort{|e| -e}
51 52 53 |
# File 'lib/rubyhelper/arrayhelper.rb', line 51 def maxs(n=1) return Array(self.sort[(-n)..(-1)]) end |
#sum ⇒ Object
34 35 36 |
# File 'lib/rubyhelper/arrayhelper.rb', line 34 def sum return (self.size > 0) ? (self.map{|e| e.to_s.to_i}.reduce(:+)) : (0) end |
#sumf ⇒ Object
38 39 40 |
# File 'lib/rubyhelper/arrayhelper.rb', line 38 def sumf return (self.size > 0) ? (self.map{|e| e.to_s.to_f}.reduce(:+)) : (0.0) end |
#to_clean_s(sep = ' ') ⇒ Object
A simple function like to_s(), but return a clean String for exemple :
[1,2,3].to_clean_s(" ; ")
> “1 ; 2 ; 3”
Parameters:
sep:
A String to separe each element (or an Array, see to_clean_s_with_array)
12 13 14 15 |
# File 'lib/rubyhelper/arrayhelper.rb', line 12 def to_clean_s(sep=' ') return to_clean_s_with_array(sep) if sep.is_a?Array to_clean_s_with_string(sep.to_s) end |
#to_clean_s_with_array(sep) ⇒ Object
You can use an array as separator : [“,”, “ ”] will successively ‘,’ and ‘ ’
24 25 26 27 28 29 30 31 32 |
# File 'lib/rubyhelper/arrayhelper.rb', line 24 def to_clean_s_with_array sep str = String.new i = 0 self.each do |e| str = str + e.to_s + sep[i % sep.size].to_s i += 1 end return str[0..(-sep.size - 1)] end |
#to_clean_s_with_string(sep) ⇒ Object
17 18 19 20 21 |
# File 'lib/rubyhelper/arrayhelper.rb', line 17 def to_clean_s_with_string sep str = String.new self.each{|e| str = str + e.to_s + sep.to_s} return str[0..(-sep.size - 1)] end |