Class: Array

Inherits:
Object show all
Defined in:
lib/array/fetch_nested.rb,
lib/array/squeeze.rb,
lib/array/permutation2.rb

Overview

Note: this file is exactly the same as Hash#fetch_nested except the class name.

Instance Method Summary collapse

Instance Method Details

#fetch_nested(*keys) ⇒ Object Also known as: dig

nil safe version of Hash#[]. a.fetch_nested(*) is basically the same as a.try.send(:[],1).



6
7
8
9
10
11
12
# File 'lib/array/fetch_nested.rb', line 6

def fetch_nested(*keys)
	begin
		keys.reduce(self){|accum, k| accum.fetch(k)}
	rescue (RUBY_VERSION<'1.9' ? IndexError : KeyError)
		block_given? ? yield(*keys) : nil
	end
end

#permutation2(n = self.size) {|a.dup[0,n]| ... } ⇒ Object

Enumerates permutation of Array. Unlike Array#permutation, there are no duplicates in generated permutations. Instead, elements must be comparable.

Yields:

  • (a.dup[0,n])


5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/array/permutation2.rb', line 5

def permutation2(n=self.size)
	return to_enum(:permutation2,n) unless block_given?
	return if n<0||self.size<n
	a=self.sort
	yield a.dup[0,n]
	loop{
		a=a[0,n]+a[n..-1].reverse
		k=(a.size-2).downto(0).find{|i|a[i]<a[i+1]}
		break if !k
		l=(a.size-1).downto(k+1).find{|i|a[k]<a[i]}
		a[k],a[l]=a[l],a[k]
		a=a[0,k+1]+a[k+1..-1].reverse
		yield a.dup[0,n]
	}
end

#squeeze!Object

Destructive version of Enumerable#squeeze



3
4
5
# File 'lib/array/squeeze.rb', line 3

def squeeze!
	replace(squeeze)
end