Permalink
Browse files

Added support for '==='.

  • Loading branch information...
1 parent 3d1d237 commit 00a2a0a422bb9f59ef2657041fba073bb2917d8c @hannesg hannesg committed Sep 18, 2012
Showing with 44 additions and 1 deletion.
  1. +16 −0 README.markdown
  2. +15 −1 lib/ampex.rb
  3. +13 −0 spec/ampex_spec.rb
View
@@ -35,6 +35,13 @@ You can use this in any place a block is expected, for example to create a lambd
normalizer.call :HelloWorld
# => "helloworld"
+Last but definitly not least you can use this as a target for `when` like this
+
+ case( something )
+ when X.respond_to? :foo then "something responds to :foo"
+ when X.kind_of? Hash then "something is a Hash"
+ end
+
Gotchas
-------
@@ -64,6 +71,15 @@ Secondly, other arguments or operands will only be evaluated once, and not every
[1, 2].map{ |x| x + (i += 1) }
# => [2, 4]
+
+Thirdly, `#===` only works on `X` itself.
+
+ # Correct
+ [1,2,3].map(&X === 2) #=> [false, true, false]
+
+ # Wrong:
+ [1,2,3].map(&X.class === Fixnum) #! raises an exception
+
Epilogue
--------
View
@@ -23,6 +23,17 @@ def initialize(&block)
@to_proc = block || ::Proc.new{|x| x}
end
+ # This method is here so that a metavariable can be used as a target for "when" like this:
+ #
+ # case( foo )
+ # when X.respond_to? :bar then "Responds to :bar"
+ # when X.respond_to? :foobar then "Responds to :foobar"
+ # end
+ #
+ def ===(y)
+ to_proc === y
+ end
+
# Each time a method is called on a Metavariable, we want to create a new
# Metavariable that is like the last but does something more.
#
@@ -42,8 +53,11 @@ def method_missing(name, *args, &block)
# BlankSlate and BasicObject have different sets of methods that you don't want.
# let's remove them all.
instance_methods.each do |method|
- undef_method method unless %w(method_missing to_proc __send__ __id__).include? method.to_s
+ undef_method method unless %w(method_missing to_proc __send__ __id__ ===).include? method.to_s
end
end
X = Metavariable.new
+class << X
+ undef ===
+end
View
@@ -55,4 +55,17 @@ def sign_off; "Yours relatedly, Cousin Sybil"; end
[A.new].map(&X.sign_off).should == ["Yours relatedly, Cousin Sybil"]
end
+ it "should be a valid target for when" do
+
+ (X.kind_of?(Numeric) === "String").should be_false
+
+ end
+
+ it "should not override X#===" do
+
+ [1,2,3].map(&X === 2).should == [false, true, false]
+
+ end
+
+
end

0 comments on commit 00a2a0a

Please sign in to comment.