[英]Delete Elements from an Array
我有一個看起來像下面的數組
[
[0] "The Jungle Book",
[1] {
"error" => "NO accessor for text",
"methodName" => "text",
"receiverString" => "android.widget.LinearLayout{438ce3c8 V.E..... ........ 0,65-148,111 #7f0902b0 app:id/movieScoreRtLayout}",
"receiverClass" => "android.widget.LinearLayout"
},
[2] "Bruce Reitherman, Phil Harris",
[3] "PG, 1 hr. 18 min.",
[4] {
"error" => "NO accessor for text",
"methodName" => "text",
"receiverString" => "com.flixster.android.view.UnclickableRelativeLayout{42ef9d18 V.E..... ........ 0,1-1080,275}",
"receiverClass" => "com.flixster.android.view.UnclickableRelativeLayout"
},
[5] {
"error" => "NO accessor for text",
"methodName" => "text",
"receiverString" => "android.widget.ListView{43bd1548 VFED.VC. .F...... 0,0-1080,1542 #7f0901a7 app:id/lvi_listview}",
"receiverClass" => "android.widget.ListView"
},
[6] {
"error" => "NO accessor for text",
"methodName" => "text",
"receiverString" => "android.widget.FrameLayout{42eeff30 V.E..... ........ 0,0-1080,1701 #1020002 android:id/content}",
"receiverClass" => "android.widget.FrameLayout"
},
[7] {
"error" => "NO accessor for text",
"methodName" => "text",
"receiverString" => "android.widget.FrameLayout{42e57e98 V.E..... ........ 0,0-1080,1701 #1020011 android:id/tabcontent}",
"receiverClass" => "android.widget.FrameLayout"
}
]
我希望能夠得到包含以下內容的結果數組:
["The Jungle Book" , "Bruce Reitherman, Phil Harris" , "PG, 1 hr. 18 min." ]
這是使用Enumerable#grep
的正確示例:
返回枚舉中每個包含
Pattern === element
。 如果提供了可選塊,則將每個匹配元素傳遞給它,並將該塊的結果存儲在輸出數組中 。
a = [
"The Jungle Book",
{ "error" => "NO accessor for text", },
"Bruce Reitherman, Phil Harris",
"PG, 1 hr. 18 min.",
{ "error" => "NO accessor for text", },
{ "error" => "NO accessor for text", },
{ "error" => "NO accessor for text", },
{ "error" => "NO accessor for text", }
]
a.grep(String)
# => ["The Jungle Book", "Bruce Reitherman, Phil Harris", "PG, 1 hr. 18 min."]
使用Array#delete_if
,您可以刪除非字符串元素:
a = [
"The Jungle Book",
{ "error" => "NO accessor for text", },
"Bruce Reitherman, Phil Harris",
"PG, 1 hr. 18 min.",
{ "error" => "NO accessor for text", },
{ "error" => "NO accessor for text", },
{ "error" => "NO accessor for text", },
{ "error" => "NO accessor for text", }
]
a.delete_if { |x| ! x.is_a? String } # OR a.delete_if { |x| x.is_a? Hash }
a
# => ["The Jungle Book", "Bruce Reitherman, Phil Harris", "PG, 1 hr. 18 min."]
或者像Arupt Rakshit所評論的那樣,您可以使用Array#select!
或Array#keep_if
:
a.select! { |x| x.is_a? String }
a.keep_if { |x| x.is_a? String }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.