Created
July 2, 2012 02:24
-
-
Save scottymac/3030565 to your computer and use it in GitHub Desktop.
Array#to_enum
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
class Array | |
def to_enum | |
Array.new(self.size, &lambda { |n| self[n].is_a?(Hash) ? self[n] : {:"#{self[n]}" => n}} ).inject({}) {|m, w| m.merge!(w) } | |
end | |
end | |
FRUIT = [:apple, :orange, :strawberry].to_enum | |
puts FRUIT[:apple] | |
>> 0 | |
puts FRUIT[:orange] | |
>> 1 | |
puts FRUIT[:strawberry] | |
>> 2 | |
COLORS = [{:red => 6}, :green, :blue].to_enum | |
puts COLORS[:red] | |
>> 6 | |
puts COLORS[:green] | |
>> 1 | |
puts COLORS[:blue] | |
>> 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment