从阵列中删除元素

时间:2014-02-16 09:45:42

标签: ruby arrays

我有一个如下所示的数组

[
[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." ]

2 个答案:

答案 0 :(得分:3)

这是使用Enumerable#grep的正确示例:

  

返回 enum Pattern === element的每个元素的数组。如果提供了可选块,则将每个匹配元素传递给它,并将块的结果存储在输出 array 中。

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."]

答案 1 :(得分:1)

使用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 }