Permalink
Browse files

Add Array#init

  • Loading branch information...
1 parent 29781fd commit 4002650ac30a331293c3d199ec6881d9e85c9fdc @bbatsov committed Aug 24, 2013
Showing with 28 additions and 0 deletions.
  1. +1 −0 README.md
  2. +1 −0 lib/powerpack/array.rb
  3. +15 −0 lib/powerpack/array/init.rb
  4. +11 −0 spec/powerpack/array/init_spec.rb
View
@@ -22,6 +22,7 @@ Or install it yourself as:
## Extensions
* [Array](http://rdoc.info/github/bbatsov/powerpack/Array)
+ * [#init](http://rdoc.info/github/bbatsov/powerpack/Array#init-instance_method)
* [#tail](http://rdoc.info/github/bbatsov/powerpack/Array#tail-instance_method)
* [Hash](http://rdoc.info/github/bbatsov/powerpack/Hash)
* [#symbolize_keys](http://rdoc.info/github/bbatsov/powerpack/Hash#symbolize_keys-instance_method)
View
@@ -1 +1,2 @@
+require_relative 'array/init'
require_relative 'array/tail'
@@ -0,0 +1,15 @@
+unless Array.method_defined? :init
+ class Array
+ # Returns a new array that has all the elements of the current but the last.
+ #
+ # @return [Array] a new array without the last element or empty array if this
+ # array is empty
+ #
+ # @example
+ # [1, 2, 3].init #=> [1, 2]
+ # [].init #=> []
+ def init
+ self[0...-1]
+ end
+ end
+end
@@ -0,0 +1,11 @@
+require 'spec_helper'
+
+describe 'Array#init' do
+ it 'returns an array without the last element' do
+ expect([1, 2, 3].init).to eq([1, 2])
+ end
+
+ it 'returns [] for empty lists' do
+ expect([].init).to be_empty
+ end
+end

0 comments on commit 4002650

Please sign in to comment.