bind(1.5)[4] # =>
# ~> -:16:in `bind': bind argument must be an instance of Fixnum (TypeError)
# ~> from -:16
We get this error because + is defined in Fixnum; therefore, the UnboundMethod object
we receive must be bound to an object that is a kind_of?(Fixnum). Had the + method
been defined in Numeric (from which both Fixnum and Float inherit), the preceding
code would have returned 5.5.
Blocks to Procs and Procs to blocks
One downside to the current implementation of Ruby: blocks are not always Procs,
and vice versa. Ordinary blocks (created with do...end or { }) must be attached to a
method call, and are not automatically objects. For example, you cannot say code_
block = { puts "abc" }. This is what the Kernel#lambda and Proc.new functions are for:
converting blocks to Procs.*
block_1 = lambda { puts "abc" } # => #
block_2 = Proc.new { puts "abc" } # => #
There is a slight difference between Kernel#lambda and Proc.new. Returning from a
Proc created with Kernel#lambda returns the given value to the calling function;
returning from a Proc created with Proc.new attempts to return from the calling function,
raising a LocalJumpError if that is impossible. Here is an example:
def block_test
lambda_proc = lambda { return 3 }
proc_new_proc = Proc.new { return 4 }
* Kernel#proc is another name for Kernel#lambda, but its usage is deprecated.
Pages:
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48