Skip to content

Instantly share code, notes, and snippets.

@elado
Created July 9, 2012 09:38
Show Gist options
  • Save elado/3075358 to your computer and use it in GitHub Desktop.
Save elado/3075358 to your computer and use it in GitHub Desktop.
Some Ruby Array methods
class Array
def pinject(memo, &block)
inject(memo) { |all, curr| block.call(all, curr); all }
end
def hash_by
return {} unless block_given?
pinject({}) { |all, curr|
# yield = block to extract key from an item
key = yield(curr)
all[key] = curr if key
}
end
def grouped_hash_by
return {} unless block_given?
pinject({}) { |all, curr|
# yield = block to extract key from an item
(all[yield(curr)] ||= []) << curr
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment