class Array
Note: this file is exactly the same as Hash#fetch_nested
except the class name.
Public Instance Methods
fetch_nested(*keys) { |*keys| ... }
click to toggle source
nil safe version of Hash#[].
a.fetch_nested(*[0,1]) is basically the same as a[0].try.send(:[],1).
# 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
Also aliased as: dig
permutation2(n=self.size) { |dup| ... }
click to toggle source
Enumerates permutation of Array
. Unlike Array#permutation, there are no duplicates in generated permutations. Instead, elements must be comparable.
# 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!()
click to toggle source
Destructive version of Enumerable#squeeze
# File lib/array/squeeze.rb, line 3 def squeeze! replace(squeeze) end