April 6, 2009
Improving Ruby Array class
By Pablo Ifran
Improving the ruby Array class
Many times, when you are iterating over an array you want to know the last or the first element to do something. Unfortunately ruby don’t provide any method to help you doing this task.
So, if you want a trick to do this, you can add this few lines in a rails project inside an initalizer.
Put this code in initializers/array.rb
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 |
class Array # array.each_with_first {|item, first| block } -> array # # # Call a <em>block</em> ones per element, passing # the element and the first element of the array as parameters. # # a = [ "a", "b", "c" ] # a.each_with_first {|x, f| print "#{x} -- #{f} | " } # # produces: # # a -- a | b -- a | c -- a | # def each_with_first(&block) first = self.first self.each do |element| yield element, first end end # array.each_with_last {|item, last| block } -> array # # # Call a <em>block</em> ones per element, passing # the element and the last element of the array as parameters. # # a = [ "a", "b", "c" ] # a.each_with_last {|x, f| print "#{x} -- #{f} | " } # # produces: # # a -- c | b -- c | c -- c | # def each_with_last(&block) last = self.last self.each do |element| yield element, last end end # array.each_with_first_and_last {|item, first, last| block } -> array # # # Call a <em>block</em> ones per element, passing # the element, the first and the last element of the array as parameters. # # a = [ "a", "b", "c" ] # a.each_with_last {|x, f, l| print "#{x} -- #{f} -- #{l} | " } # # produces: # # a -- a -- c | b -- a -- c | c -- a -- c | # def each_with_first_and_last(&block) first = self.first last = self.last self.each do |element| yield element, first, last end end end |