[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Newb Newb

8/22/2008 4:29:00 AM

src_array = imgs.collect{|img| img.attributes["src"]}

can you people explain this code => imgs.collect{|img|
img.attributes["src"]}
--
Posted via http://www.ruby-....

1 Answer

Jesús Gabriel y Galán

8/22/2008 5:56:00 AM

0

On Fri, Aug 22, 2008 at 6:29 AM, Newb Newb <hema@angleritech.com> wrote:
> src_array = imgs.collect{|img| img.attributes["src"]}
>
> can you people explain this code => imgs.collect{|img|
> img.attributes["src"]}

The method collect comes from the Enumerable module:

http://www.ruby-doc.org/core/classes/Enumerable.ht...

As it explains in the documentation, it runs the block of code once for
each value in the enumerable (imgs), yielding it to the block, and putting
all the result values in an array. An example in which imgs is an
array of strings:

irb(main):001:0> imgs = %w{img1 img2 img3 img4}
=> ["img1", "img2", "img3", "img4"]
irb(main):003:0> imgs.collect {|img| img.upcase}
=> ["IMG1", "IMG2", "IMG3", "IMG4"]

So, it passes each value of imgs to the block, storing the result
value of the block in an array, which is the result of the collect method.

In your case, each object in the enumerable is not a string, but some object
that has a method attributes. From your other emails, I think you
might be talking
about Hpricot nodes. In that case img.attributes["src"] will return
the attribute
"src" from an image tag. So you will end up with an array containing all the src
attributes of the images present in imgs.

Hope this helps,

Jesus.