diff --git a/lib/rackstash/fields/array.rb b/lib/rackstash/fields/array.rb index a64ef68..59c7520 100644 --- a/lib/rackstash/fields/array.rb +++ b/lib/rackstash/fields/array.rb @@ -159,6 +159,22 @@ module Rackstash self end + # Removes the last element from `self` and returns it, or `nil` if the + # array is empty. If a number `n` is given, returns an array of the last + # `n` elements (or less). + # + # See {#push} for the opposite effect. + # + # @param n [Integer, nil] the (optional) number of elements to return from + # the end + # @return [Object, Array, nil] If `n` was given, we always return + # an array with at most `n` elements. Else, we return the last element + # or `nil` if the array is empty. + # + def pop(n = nil) + n.nil? ? @raw.pop : @raw.pop(n) + end + # Append — Pushes the given object(s) on to the end of this array. All # values will be normalized before being added. This method returns the # array itself, so several appends may be chained together. diff --git a/spec/rackstash/fields/array_spec.rb b/spec/rackstash/fields/array_spec.rb index aed729c..8468fa0 100644 --- a/spec/rackstash/fields/array_spec.rb +++ b/spec/rackstash/fields/array_spec.rb @@ -268,6 +268,27 @@ describe Rackstash::Fields::Array do end end + describe '#pop' do + it 'returns nothing from an empty array' do + expect(array.pop).to be_nil + expect(array.pop(42)).to be_instance_of(Array).and be_empty + end + + it 'returns and removes the last element' do + array << 'foo' << 'bar' + + expect(array.pop).to eql 'bar' + expect(array[0]).to eql 'foo' + end + + it 'returns and removes at most n elements' do + array << 'foo' << 'bar' << 'baz' + + expect(array.pop(2)).to eql ['bar', 'baz'] + expect(array[0]).to eql 'foo' + end + end + describe '#push' do it 'can append multiple values' do expect(array.push 'value', 'value2').to equal array