From: Evan Martin Date: 2002-06-13T02:40:01+09:00 Subject: procs and blocks When a need to use a callback function, it seem there are two ways to go about doing it: 1) Take a block: def set_cb_1(&p) $cb = p end (or, similarly,) def set_cb_1 $cb = Proc.new # Proc.new by default wraps the block end 2) Take a Proc: def set_cb_2(p) $cb = p end To use these functions, then: set_cb_1 { ... } set_cb_1 do ... end or set_cb_2 proc { ... } set_cb_2 Proc.new { ... } and if I make a function def somefunc ... end I can use it like: seb_cb_1 { somefunc() } set_cb_2 method("somefunc") # weird Are they equivalent? Are the two forms of set_cb_1 I wrote above the same thing? It seems the first one sets $cb to a block, while the latter sets $cb to a proc that wraps a block. Or are a proc and a block the same thing? Is either way considered preferable? I'm wrapping a C library that uses callbacks, and I found myself writing this code, where I explicitly support both (ignore that "type" variable, it's unrelated to this): if (rb_block_given_p()) { rb_scan_args(argc, argv, "1&", &type, &cb); /* behaves like set_cb_1; cb is the provided block */ } else { rb_scan_args(argc, argv, "2", &type, &cb); /* behaves like set_cb_2; cb is the explicitly passed proc */ } It seems they should almost be the same thing? -- Evan Martin martine@cs.washington.edu http://neugierig.org