从红宝石数组,如果条件得到价值 [英] get values from ruby array if condition
本文介绍了从红宝石数组,如果条件得到价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我映射这个code a数组:
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"]
对于这种情况,3的值。
感谢您
推荐答案
您可以致电阵列的紧凑
方法,从它删除空的结果。
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
这篇关于从红宝石数组,如果条件得到价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文