Can someone please explain this line of code?

From Agile Rails Development:

current_item = @items.find {|item| item.product == product}

it's at the start of the "add_product" method in the model "cart"

It finds an entry in the @items list whose product attribute equals the parameter product. If none exists, it sets current_item to nil.

Dave

Thank you!

The book rocks by the way!

Get thee behind me, Satan...

Hi --

The unusual looking |item| construct at the beginning of the code block
is just how Ruby allows the programmer to say "for each one of the
things you're about to pass me, I'm going to call them 'item' in this
code block".

It also has implications if you already have a variable called item --
namely, it will assign to *that* variable. (In Ruby 1.8 and earlier,
that is.) That can be advantageous (which is why I'm sad that it's
disappearing), but also means one has to be careful in choosing a
variable name since it could have an effect outside the block.

The code block could just as easily been {|Dave|
Dave.product == product} and it would work the same way. Using "item"
just makes more sense.

You wouldn't want to use a constant there, though. It will run, but
you'll get warnings.

How'd I do Dave?

Whoops, I'm the wrong Dav(e|id). I'm just pinch-hitting :slight_smile:

David

Thanks for taking the time to write that reply - Unfortunately I can't
read that many books all at once, although I'd point out that Dave
Thomas is co-author (with DHH) of the book I am going through (Agile
Web Development with Rails 2nd Ed.). I'll get to "Programming Ruby"
soon enough, I'm pretty much addicted to how cool this framework is.

I think it's great that everyone is so involved in the community that a
newbie like me posts a rather basic question, and gets replys from two
very notable Dave's (Thomas and Black) and a very well thought out
response from you.

Thanks everyone!!

Thanks for taking the time to write that reply - Unfortunately I can't
read that many books all at once, although I'd point out that Dave
Thomas is co-author (with DHH) of the book I am going through (Agile
Web Development with Rails 2nd Ed.). I'll get to "Programming Ruby"
soon enough, I'm pretty much addicted to how cool this framework is.

I think it's great that everyone is so involved in the community that a
newbie like me posts a rather basic question, and gets replys from two
very notable Dave's (Thomas and Black) and a very well thought out
response from you.

Thanks everyone!!