Skip to content

Instantly share code, notes, and snippets.

@scottymac
Created July 2, 2012 02:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottymac/3030565 to your computer and use it in GitHub Desktop.
Save scottymac/3030565 to your computer and use it in GitHub Desktop.
Array#to_enum
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