String

N

Newb Newb

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

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

Jesús Gabriel y Galán

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,201
Messages
2,571,051
Members
47,656
Latest member
rickwatson

Latest Threads

Top