Steven Taylor wrote:
To me, it appears as if the method has to be read in
conjunction with how the method is actually called in order to know if a
block is passed or not.
Not necessarily:
def meth1
yield
end
meth1 {puts “hello”}
–output:–
hello
meth1
–output:–
r1test.rb:2:in `meth1’: no block given (LocalJumpError)
from r1test.rb:7
So by reading the definition of meth1, you know that a block has to be
passed in the method call. As for knowing what block is passed, yes,
you might have to look through 100’s of lines of code to discover that.
On the other hand, if the method definition looks like this:
def mymeth(an_int)
if block_given?
yield an_int
else
puts “hi”
end
end
then you don’t know if the method will be called with a block:
mymeth(3) {|val| puts val}
–output:–
3
mymeth(3)
–output:–
hi
But is that much different from looking at this method definition:
def somemeth(x):
if x==“yes”
#40,000 function calls go here, which
#open 50 sockets
#awaken 20 million zomby computers
#search for nuclear launch codes with brute force attacks
#send launch codes to world news organizations to show how
vulnerable world security is
else
puts “have a nice day”
end
end
and thinking…Gee, I don’t know what that method will do unless I can
track down the method call and observe the value of x? And then what if
you find:
somemeth(calc_x)
In other words, the method calls another method to calculate its
argument.
If my assertion is correct then the actual
method call(s) in source code could be 100’s of lines away from the
method definition.
Heck, in Java method calls probably won’t even be in the same file as
the method definition. And in C++, normally an include directive is
used to link function definitions in other files to the function calls
in the current file, which means the function definitions won’t be
visible in the current file either.
What if you define a function called myfunc in C++ that takes another
function as an argument? The following is a C++ program that does just
that. Can you tell what myfunc does (*answer below)?
File 1:
//main.cpp
#include
#include “globals.h”
#include “otherfuncs.h”
using namespace std;
int main()
{
myfunc(addEm); //<–function call. What the heck does that do?
return 0;
}
==============
Supporting files:
File 2:
//otherfuncs.h
#ifndef OTHERFUNCS_H
#define OTHERFUNCS_H
int addEm(int x, int y);
#endif
File 3:
//otherfuncs.cpp
#include “otherfuncs.h”
int addEm(int x, int y)
{
return x + y;
}
File 4:
//globals.h
#ifndef GLOBALS_H
#define GLOBALS_H
void myfunc(int (*pfunc)(int, int));
#endif
File 5:
#include “globals.h”
using namespace std;
void myfunc(int (*pfunc)(int, int) )
{
cout<<pfunc(3, 4)<<endl;
}
myfunc displays 7 to the screen.