From: Matt Mongeau Date: 2013-04-13T05:19:51+09:00 Subject: Re: Trying to understand blocks --089e01681d16f9987b04da2f9f1c Content-Type: text/plain; charset=ISO-8859-1 Blocks are special arguments to methods. You can pass blocks 3 ways* foo { puts "bar" } foo do puts "bar" end proc = lambda { puts "bar" } foo(&proc) The reason for the & in the 3rd example is to tell ruby that this argument is actually this "special" block parameter. The yield method knows to look for this special parameter and call it. On Fri, Apr 12, 2013 at 4:12 PM, Vincent Stowbunenko wrote: > I am confused about what is going on with this code: > > > def foo > yield("Jim") > end > > def bar > baz = lambda { |n| n.upcase } > foo(&baz) > end > > bar # => "JIM" > > > From what I understand where this is going: > > 1. The method bar is being called. > > 2. Inside the bar method, the lambda function is being assigned to the > baz variable, to upcase whatever is assigned to the variable n inside > the lambda function. > > 3. I don't understand the use of ampersand operator associated with the > variable baz. Whatever that is, it is an argument for the foo method. > > 4. Inside the foo method, it uses a yield function with an argument > "Jim". Somehow, the string "Jim" made it way to assign to the variable > n, upcasing it. > > > Can anyone help me clarify what this code is really doing? > > -- > Posted via http://www.ruby-forum.com/. > > --089e01681d16f9987b04da2f9f1c Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable
Blocks are special arguments to methods. You can pass bloc= ks 3 ways*

foo { puts "bar" }
foo do
=A0 puts "bar"
end

proc =3D lambda { puts "bar" }
foo(&proc)

The reaso= n for the & in the 3rd example is to tell ruby that this argument is ac= tually this "special" block parameter.

The yield method knows to look for this spe= cial parameter and call it.


<= div class=3D"gmail_quote">On Fri, Apr 12, 2013 at 4:12 PM, Vincent Stowbune= nko <lists@ruby-forum.com> wrote:
I am confused about what is going on with th= is code:


def foo
=A0 =A0 yield("Jim")
end

def bar
=A0 =A0baz =3D lambda { |n| n.upcase }
=A0 =A0foo(&baz)
end

bar # =3D> "JIM"


From what I understand where this is going:

1. The method bar is being called.

2. Inside the bar method, the lambda function is being assigned to the
baz variable, to upcase whatever is assigned to the variable n inside
the lambda function.

3. I don't understand the use of ampersand operator associated with the=
variable baz. =A0Whatever that is, it is an argument for the foo method.
4. Inside the foo method, it uses a yield function with an argument
"Jim". =A0Somehow, the string "Jim" made it way to assi= gn to the variable
n, upcasing it.


Can anyone help me clarify what this code is really doing?

--
Posted via http://= www.ruby-forum.com/.


--089e01681d16f9987b04da2f9f1c--