Skip to content

Small mixin for Objects in Ruby 1.9 that allows classes to automate setting up the usual ".nonzero? or" chain of comparisons in <=>.

Notifications You must be signed in to change notification settings

texaswilliam/easycmp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

36 Commits
 
 
 
 
 
 

Repository files navigation

This is a small mixin for Object that allows classes to automate setting up the usual ".nonzero? or" chain of comparisons in <=>.

Usage:
  require 'easycmp'
  class MyClass
    easy_cmp :bar
    easy_cmp :@foo
    #OR easy_cmp :bar,:@foo
  end

  is equivalent to:

  class MyClass
    def <=> oth
      (self.call(:bar)<=>oth.call(:bar)).nonzero? or
        self.instance_variable_get(:@foo)<=>oth.instance_variable_get(:@foo)
    end
  end

Options:
  append defaults to true. If set to false, all fields will be cleared before adding the given fields.
      easy_cmp :bar
      easy_cmp :@foo, append: false
      easy_cmp :@baz
    is equivalent to:
      easy_cmp :@foo,:@baz

  reverse defaults to false. If set to true, the fields define in its easy_cmp call will be compared in reverse.
    class MyClass
      easy_cmp :@foo
      easy_cmp :@bar, reverse: true
      def initialize foo, bar
        @foo=foo
        @bar=bar
      end
    end
    MyClass.new(1,0)<=>MyClass.new(0,0)
    => 1
    MyClass.new(0,1)<=>MyClass.new(0,0)
    => -1
    
Extras:
easy_cmp_clear will clear previously given fields. It can also be given a block to redefine <=> with.

Future Plans:
I certainly need to use RDoc.

About

Small mixin for Objects in Ruby 1.9 that allows classes to automate setting up the usual ".nonzero? or" chain of comparisons in <=>.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages