# String

**URL:** <https://www.ruby-forum.com/t/string/146544>\
**Category:** Ruby\
**Created:** [August 22, 2008, 6:32am UTC](https://www.ruby-forum.com/t/string/146544 "2008-08-22T06:32:52Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![newb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/2acd7d/32.png) [@newb](https://www.ruby-forum.com/u/newb)\
**Post date:** [August 22, 2008, 6:32am UTC](https://www.ruby-forum.com/t/string/146544/1 "2008-08-22T06:32:52Z")

</div>

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

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

---

<div class="post-metadata">

**Author:** ![newb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/2acd7d/32.png) [@newb](https://www.ruby-forum.com/u/newb)\
**Post date:** [August 22, 2008, 8:00am UTC](https://www.ruby-forum.com/t/string/146544/2 "2008-08-22T08:00:35Z")

</div>

On Fri, Aug 22, 2008 at 6:29 AM, Newb N. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) 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](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.
