Created
July 13, 2012 19:24
-
-
Save mboeh/3106823 to your computer and use it in GitHub Desktop.
Attempt at converting lambdas to have proc behavior
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'test/unit/testcase' | |
require 'test/unit' if $0 == __FILE__ | |
class Proc | |
def as_proc | |
if arity == -1 | |
self | |
else | |
aty = arity.abs - (arity < 0 ? 1 : 0) | |
proc{|*a| self[*a.values_at(*0...aty)] } | |
end | |
end | |
end | |
class AsProcTest < Test::Unit::TestCase | |
def test_fewer_values | |
assert_nothing_raised do | |
lambda{|a,b,c| }.as_proc[1,2] | |
end | |
assert_equal [1,2,nil], lambda{|a,b,c| [a,b,c] }.as_proc[1,2] | |
end | |
def test_variable_args | |
assert_nothing_raised do | |
lambda{|*a| }.as_proc[1,2,3,4] | |
end | |
assert_equal [1,2,3], lambda{|*a| a}.as_proc[1,2,3] | |
# In Ruby 1.8, procs become lambda-y if given a splat arg | |
if RUBY_VERSION.to_f >= 1.9 | |
assert_nothing_raised do | |
lambda{|a,b,*c| }.as_proc[1] | |
end | |
assert_equal [1,nil,[]], proc{|a,b,*c| [a,b,c] }[1] | |
assert_equal [1,nil,[]], lambda{|a,b,*c| [a,b,c] }.as_proc[1] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment