Module: HashMultiTool
- Defined in:
- lib/hash_multi_tool.rb,
lib/hash_multi_tool/version.rb
Constant Summary collapse
- VERSION =
"0.1.5"
Class Method Summary collapse
- .collect_keys(h_object) ⇒ Object
- .select_by_key_value(hash = [], key = [], value = nil) ⇒ Object
- .sort_asc(hash) ⇒ Object
- .sort_by_order(hash = [], order = [], direction = 'ASC') ⇒ Object
- .sort_desc(hash) ⇒ Object
- .transpose_to_array(hash = {}) ⇒ Object
- .transpose_to_hash(arr = []) ⇒ Object
- .values_to_percentage(hash) ⇒ Object
Class Method Details
.collect_keys(h_object) ⇒ Object
18 19 20 21 22 23 24 25 26 |
# File 'lib/hash_multi_tool.rb', line 18 def collect_keys h_object if h_object.is_a? Hash (h_object.keys + collect_keys(h_object.values)).flatten.uniq elsif h_object.is_a? Array h_object.collect{|value| collect_keys value} else [] end end |
.select_by_key_value(hash = [], key = [], value = nil) ⇒ Object
14 15 16 |
# File 'lib/hash_multi_tool.rb', line 14 def select_by_key_value hash = [], key = [], value = nil hash.select { |h| h[key] == value } end |
.sort_asc(hash) ⇒ Object
46 47 48 |
# File 'lib/hash_multi_tool.rb', line 46 def sort_asc hash Hash[hash.sort_by {|k, v| v}] end |
.sort_by_order(hash = [], order = [], direction = 'ASC') ⇒ Object
5 6 7 8 9 10 11 12 |
# File 'lib/hash_multi_tool.rb', line 5 def sort_by_order hash = [], order = [], direction ='ASC' hash.sort do |a,b| a_arr = [] b_arr = [] order.each{|key| a_arr << a[key]; b_arr << b[key];} direction.downcase == "desc" ? b_arr <=> a_arr : a_arr <=> b_arr end end |
.sort_desc(hash) ⇒ Object
42 43 44 |
# File 'lib/hash_multi_tool.rb', line 42 def sort_desc hash Hash[hash.sort_by {|k, v| -v}] end |
.transpose_to_array(hash = {}) ⇒ Object
35 36 37 38 39 40 |
# File 'lib/hash_multi_tool.rb', line 35 def transpose_to_array hash = {} hash.inject([]){|a, (k,vs)| vs.each_with_index{|v,i| (a[i] ||= {})[k] = v} a } end |
.transpose_to_hash(arr = []) ⇒ Object
28 29 30 31 32 33 |
# File 'lib/hash_multi_tool.rb', line 28 def transpose_to_hash arr = [] arr.inject({}){|a, h| h.each_pair{|k,v| (a[k] ||= []) << v} a } end |
.values_to_percentage(hash) ⇒ Object
50 51 52 53 54 55 56 57 |
# File 'lib/hash_multi_tool.rb', line 50 def values_to_percentage hash if (hash.values.map{|val| val.is_a? Fixnum || Float }).all? {|boolean| boolean == true} sum = hash.values.inject 0, :+ hash.each { |k,v| hash[k] = (v*100/sum.to_f).round(2) } else 'Percentage can only be calculated for numbers or decimals' end end |