1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
# A set of monkey patches for the ruby programmer who isn't yet satisified with the core library class Object # useful for reflection def local_methods(obj = self) (obj.methods - obj.class.superclass.instance_methods).sort end end class String # does the string look numeric? def num? Float(self) rescue false end end class Integer # 1 is true and 0 is false def c_truth {1 => true, 0 => false}[self] end end class Numeric # improves polymorphism of String#num? def num? # This is obviously numeric because it's Numeric aha! true end end class Hash # remove stuff from a hash with an array (or single value) of keys def remove(keys) copy = clone keys = [keys] unless keys.respond_to?(:each) keys.each { |e| copy.delete(e) } copy end # I particuarly like these alias - remove alias + merge end module Enumerable # all the indexes for which block yields, which is passed values, is true def detect_all_indexes detected = [] each_with_index { |e, i| detected << i if yield e } detected end # same as above only breaks after first successful detection def detect_index detected = nil each_with_index do |e, i| if yield e detected = i break end end detected end # damn that's a lot of aliases, oh sorry alices :-P alias detect_all_indices detect_all_indexes alias detect_all_indices detect_all_indexes alias find_all_indexes detect_all_indexes alias find_all_indices detect_all_indexes alias find_index detect_index end unless defined?(__method__) # already defined in ruby 1.9 # returns the name of the current method def __method__ caller[0][/`([^']*)'/, 1].to_sym end alias __callee__ __method__ end if __FILE__ == $0 require "test/unit/ui/console/testrunner" class NewDetects < Test::Unit::TestCase def test_detect_first_index assert_equal(2, %w{a b c d}.detect_index { |e| e == 'c' }) end def test_detect_index assert_equal([1,3,5], %w{a b1 c d2 e f3 g}.detect_all_indexes { |e| e =~ /\d/ }) end end Test::Unit::UI::Console::TestRunner.run(NewDetects) # not much test coverage, this is unlike me end
Refactorings
No refactoring yet !
I find ruby's core library sorely lacking very often. For me the jury is still out as to whether monkey patching is bad or not anyway, I find these useful. If you do too then maybe a gem should happen. Is there one for this kind of thing already?
Whoops, a guy got back to me on IRC about Facets... I'm going to post this anyway. Ciao!