Created
July 24, 2010 15:59
-
-
Save caius/488777 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Array#inject_with_index | |
| class Array | |
| def inject_with_index default=nil, &block | |
| self.inject(default) do |obj, element| | |
| block[obj, element, index(element)] | |
| end | |
| end | |
| end | |
| a = [:a, :b, :c].inject_with_index({}) do |hash, element, index| | |
| hash[element] = index + 1 | |
| hash | |
| end | |
| p a | |
| __END__ | |
| {:b=>2, :c=>3, :a=>1} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module Enumerable | |
| def inject_with_index default=nil, &block | |
| if self.respond_to?(:index) | |
| inject_block = lambda do |obj, element| | |
| block[obj, element, index(element)] | |
| end | |
| else | |
| counter = -1 | |
| inject_block = lambda do |obj, element| | |
| block[obj, element, counter += 1] | |
| end | |
| end | |
| self.inject default, &inject_block | |
| end | |
| end | |
| a = [:a, :b, :c].inject_with_index({}) do |hash, element, index| | |
| hash[element] = index + 1 | |
| hash | |
| end | |
| a # => {:c=>3, :b=>2, :a=>1} | |
| b = (0..5).inject_with_index({}) do |hash, element, index| | |
| hash[element] = index | |
| hash | |
| end | |
| b # => {5=>5, 0=>0, 1=>1, 2=>2, 3=>3, 4=>4} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment