String

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

can you people explain this code => imgs.collect{|img|
img.attributes[“src”]}

On Fri, Aug 22, 2008 at 6:29 AM, Newb N. [email protected] 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.html#M003158

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.