Sha256: e13ca566175567c838412a89dec5978339863230f0479548a4c73c9149d43fd7

Contents?: true

Size: 1.03 KB

Versions: 8

Compression:

Stored size: 1.03 KB

Contents

# Pattern extends Array with case equality to provide meaningful semantics in
# case statements.
#
# After this change, pattern matching-like behavior is possible with
# Arrays:
#
#     Pattern[Fixnum, String] === [1, "foo"]
#     Pattern[Symbol, Array] === [:foo, [1, 2]]
#
# When used in a case statement, it provides a functionality close to that of
# languages with proper pattern matching. It becomes useful when implementing
# a polymorphic method:
#
#     def [](index, limit = nil)
#       case [index, limit]
#       when Pattern[Fixnum, Fixnum] then
#         key.lrange(index, limit).collect { |id| model[id] }
#       when Pattern[Range, nil] then
#         key.lrange(index.first, index.last).collect { |id| model[id] }
#       when Pattern[Fixnum, nil] then
#         model[key.lindex(index)]
#       end
#     end
#
module Ohm
  class Pattern < Array
    def ===(other)
      return false if size != other.size

      each_with_index do |item, index|
        return false unless item === other[index]
      end

      true
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
ohm-0.1.5 lib/ohm/pattern.rb
ohm-0.1.4 lib/ohm/pattern.rb
ohm-0.1.3 lib/ohm/pattern.rb
ohm-0.1.2 lib/ohm/pattern.rb
ohm-0.1.1 lib/ohm/pattern.rb
ohm-0.1.0 lib/ohm/pattern.rb
ohm-0.1.0.rc6 lib/ohm/pattern.rb
ohm-0.1.0.rc5 lib/ohm/pattern.rb