Module: Enumerable
- Defined in:
- lib/rext/enumerable/helpers.rb
Defined Under Namespace
Classes: Proxy
Instance Method Summary collapse
-
#drop(n = 1, &block) ⇒ Object
Drop n elements, returning the others.
-
#every(&block) ⇒ Object
Sexy Symbol#to_proc replacement for mapping enums.
-
#group_by(&block) ⇒ Object
Return a hash grouped by
block
. -
#includes_all?(*args) ⇒ Boolean
Check if all
args
are included. -
#proxy(meth) ⇒ Object
Shortcut for Proxy.new self,
meth
. -
#take(n = 1, &block) ⇒ Object
Take n elements, or pass a block which acts as Enumerable#select.
Instance Method Details
#drop(n = 1, &block) ⇒ Object
Drop n elements, returning the others. You may also pass a block which acts as Enumerable#reject.
Examples
[1,2,3,4].drop # => [2,3,4]
[1,2,3,4].drop(2) # => [3,4]
[1,2,3,4].drop(-2) # => [1,2]
[1,2,3,4,5].drop { |n| n < 4 } # => [4,5]
101 102 103 104 105 106 107 |
# File 'lib/rext/enumerable/helpers.rb', line 101 def drop n = 1, &block case when block ; reject &block when n < 0 ; self[0...n] else self[n..-1] end end |
#every(&block) ⇒ Object
Sexy Symbol#to_proc replacement for mapping enums.
Examples
names = %w( tj scott joe bob )
names.every.length.join # => 2533
names.every.empty?.any? # => false
names.every { length > 4 }.all? # => true
71 72 73 |
# File 'lib/rext/enumerable/helpers.rb', line 71 def every &block block ? proxy(:map).instance_eval(&block) : proxy(:map) end |
#group_by(&block) ⇒ Object
Return a hash grouped by block
.
Examples
words = %w( just some foo bar )
words.group_by { |word| word.length } # => {3=>["foo", "bar"], 4=>["just", "some"]}
words.group_by { length } # => {3=>["foo", "bar"], 4=>["just", "some"]}
words.group_by.length # => {3=>["foo", "bar"], 4=>["just", "some"]}
52 53 54 55 56 57 58 |
# File 'lib/rext/enumerable/helpers.rb', line 52 def group_by &block return proxy(:group_by) unless block inject({}) do |hash, value| (hash[block.yield_or_eval(value)] ||= []) << value hash end end |
#includes_all?(*args) ⇒ Boolean
Check if all args
are included.
Examples
= 'save', 'edit', 'delete'
.includes_all? 'save', 'edit' # => true
84 85 86 |
# File 'lib/rext/enumerable/helpers.rb', line 84 def includes_all? *args args.all? { |arg| include? arg } end |
#proxy(meth) ⇒ Object
Shortcut for Proxy.new self, meth
.
37 38 39 |
# File 'lib/rext/enumerable/helpers.rb', line 37 def proxy meth Proxy.new self, meth end |
#take(n = 1, &block) ⇒ Object
Take n elements, or pass a block which acts as Enumerable#select.
Examples
[1,2,3,4].take # => [1]
[1,2,3,4].take(2) # => [1,2]
[1,2,3,4].take(-2) # => [3,4]
[1,2,3,4].take { |n| == 1 } # => [1]
121 122 123 124 125 126 127 |
# File 'lib/rext/enumerable/helpers.rb', line 121 def take n = 1, &block case when block ; select &block when n < 0 ; self[n..-1] else self[0...n] end end |