Improving the ruby Array class without degrade performance

Posted by Pablo Ifran on April 06, 2009

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

class Array

  #     array.each_with_first {|item, first| block }   ->   array
  #
  #
  # Call a block 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 block 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 block 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

[Post to Twitter] Tweet This Post 


Tweet This Post links powered by Tweet This v1.3.9, a WordPress plugin for Twitter.