# hacks, candy, overrides, etc class Hash # Usage { :a => 1, :b => 2, :c => 3}.except(:a) -> { :b => 2, :c => 3} def except(*keys) self.reject { |k,v| keys.include? k.to_sym } end # Usage { :a => 1, :b => 2, :c => 3}.only(:a) -> {:a => 1} def only(*keys) self.dup.reject { |k,v| !keys.include? k.to_sym } end end class Array # split an array based on block # ex: # strings, non_strings = [5,6,"aaa", 7, "ccc"].divorce { |element| element.is_a? String } # => [ ["aaa", "ccc"], [5,6,7] ] def divorce mom = [] dad = [] for i in 0...size value = self[i] if yield(value) mom << value else dad << value end end return [mom, dad] end def group_array_by(attribute = nil) arrays = {} for i in 0...size object = self[i] value = attribute ? object.send(attribute.to_sym) : yield(object) if arrays[value.to_s] arrays[value.to_s] << object else arrays[value.to_s] = [object] end end return arrays.values end def sum self.inject { |n,m| n += m } end end class String # replace parts of a string based on a hash # ex: # replace_hash = { "car" => "bike", "potato chips" => "apples", "store" => "fruit stand" } # my_string = "I'm going to take my car to the store and buy potato chips." # my_string.gsub_from_hash(replace_hash) # => "I'm going to take my bike to the fruit stand and buy apples." def gsub_from_hash(somehash = {}) temp = self for part in somehash unless part[0].nil? or part[1].nil? temp = temp.gsub(part[0], part[1]) end end temp end def unspace() self.gsub(" ", "_") end end