Sha256: 3b86169971df333e3f24765e951f363b328ab11b78e81720946bc4728dc3812a

Contents?: true

Size: 1.49 KB

Versions: 4

Compression:

Stored size: 1.49 KB

Contents

module Bioshogi
  class V
    class << self
      def one
        self[1, 1]
      end

      def half
        self[0.5, 0.5]
      end

      def [](...)
        new(...)
      end
    end

    attr_reader :x
    attr_reader :y

    def initialize(x, y)
      @x = x
      @y = y
      freeze
    end

    include Enumerable
    delegate :each, to: :to_a

    def to_a
      [@x, @y]
    end

    def to_ary
      to_a
    end

    def ==(other)
      @x == other.x && @y == other.y
    end

    def hash
      @x.hash ^ @y.hash
    end

    def eql?(other)
      instance_of?(other.class) && @x == other.x && @y == other.y
    end

    def <=>(other)
      to_a <=> other.to_a
    end

    %i(+ - * /).each do |op|
      class_eval <<-EOT, __FILE__, __LINE__ + 1
        def #{op}(other)                                        # def +(other)
          if other.kind_of?(self.class)                         #   if other.kind_of?(self.class)
            self.class.new(@x #{op} other.x, @y #{op} other.y)  #     self.class.new(@x + other.x, @y + other.y)
          else                                                  #   else
            self.class.new(@x #{op} other, @y #{op} other)      #     self.class.new(@x + other, @y + other)
          end                                                   #   end
        end                                                     # end
      EOT
    end

    def -@
      self * -1
    end

    def to_s
      to_a.to_s
    end

    def inspect
      "<#{self}>"
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
bioshogi-0.0.14 lib/bioshogi/v.rb
bioshogi-0.0.10 lib/bioshogi/v.rb
bioshogi-0.0.9 lib/bioshogi/v.rb
bioshogi-0.0.8 lib/bioshogi/v.rb