mardi 4 août 2015

Check how many parameters block being passed has, and then invoke yield with different parameters

I want to know if something like this is possible, as hash.each does two different things based on arguments passed to block

{ "a"=>3, "b"=>2}.each {|k| puts k}

{ "a"=>3, "b"=>2}.each {|k,v| puts k}

Both output different things, and not just what's below..

a
b
..
a
b

i get this

a
3
b
2
..
a
b

So i want to know if there is a way to get my function to do something custom depending on the number of arguments of block being passed to it.

like this

def my_method do
   if yield.args==2
     yield("hi","bro")
   else 
     yield("what's up")
   end
end

my_method {|a,b| puts a; puts b;} //"hi" "bro"

my_method {|a| puts a; } //"whats up"



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire