Question re: small piece of code

Hi,

In the example book I’m using, I ran across the following lines of code:

young_people = people.find_all do |p|
p[3].to_i.between?(20,40)
end

Now, “people” is defined by ‘p’ is not - what does that code do when it
says “do |p|”?

Thanks!

On Feb 17, 2011, at 14:17 , Gaba L. wrote:

Hi,

In the example book I’m using, I ran across the following lines of code:

young_people = people.find_all do |p|
p[3].to_i.between?(20,40)
end

Now, “people” is defined by ‘p’ is not - what does that code do when it
says “do |p|”?

‘p’ is a block variable. It is used by find_all as it enumerates people.
‘p’ contains one element from people at a time.

so the code knows that ‘p’ stands for ‘people’? what if i used another
letter, like n?

Gaba L. wrote in post #982340:

so the code knows that ‘p’ stands for ‘people’? what if i used another
letter, like n?

hi gaba -
block variables work something like this… if you set up an array:

array = [1, 2, 3, 4, 5]

and then call a method that takes a block and block variables (like
“find_all”, or in my example, “each”)

array.each{|n| puts n + 1}

the “n” (or whatever you want to use as a variable, you could just as
well use “array.each{|elephantballs| puts elephantballs + 1}”)
represents each index of the array, which are passed through the block
{puts n+1}, and give you this:

2
3
4
5
6

some methods provide for more than one block variable to be passed
into a block, you can see things like:

@artBox.signal_connect(“drag_data_received”){|widget, context, x, y,
data, info, time| self.listDataDrop(data, y)}

the ‘signal_connect(“drag_data_received”)’ method in Gtk2 provides for
the following block variables - widget, context, x position, y position,
data, info, and time (you could rename these to be anything you want,
but they will still represent these elements, in this order.) in my
example, the only variables i pass on to be used in the block are the
data, and y position, when i call “self.listDataDrop(data, y)” - but if
i cared or needed to i could pass them all along to be used…

don’t worry, you’ll get the hang of it…

-jk