Skip to content

Instantly share code, notes, and snippets.

@caius
Created July 24, 2010 15:59
Show Gist options
  • Select an option

  • Save caius/488777 to your computer and use it in GitHub Desktop.

Select an option

Save caius/488777 to your computer and use it in GitHub Desktop.
# 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}
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