Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get values from ruby array if condition

I'm mapping a array with this code:

url = "http://www.cnn.com"
page = Mechanize.new.get(url)
images_url = page.images.map{|img| img.url.to_s if (img.width.to_i > 200)}

I get this result in console:

[nil, "http://i2.cdn.turner.com/cnn/dam/assets/110929092349-nelson-mandela-t1-main.jpg", nil, nil, nil, nil, nil, "http://i2.cdn.turner.com/cnn/dam/assets/120225123812-syria-mani-2-c1-main.jpg", nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, "http://i2.cdn.turner.com/cnn/dam/assets/120225022127-blue-fish-bin-tease.jpg", nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]

I want get this array without nil values, its mean, I want get a array sth like:

["http://i2.cdn.turner.com/cnn/dam/assets/110929092349-nelson-mandela-t1-main.jpg", "http://i2.cdn.turner.com/cnn/dam/assets/120225123812-syria-mani-2-c1-main.jpg", "http://i2.cdn.turner.com/cnn/dam/assets/120225022127-blue-fish-bin-tease.jpg"]

For this case, 3 values.

Thank you

like image 218
hyperrjas Avatar asked Aug 13 '26 18:08

hyperrjas


1 Answers

You can call the compact method on your Array to remove empty results from it.

images_url = page.images.map{|img| img.url.to_s if (img.width.to_i > 200)}.compact
like image 131
Matteo Alessani Avatar answered Aug 16 '26 18:08

Matteo Alessani