Reputation: 173
I have an Array that looks like below
[
[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"
}
]
I want to be able to get the resultant array that contains the following:
["The Jungle Book" , "Bruce Reitherman, Phil Harris" , "PG, 1 hr. 18 min." ]
Upvotes: 0
Views: 90
Reputation: 369444
Using Array#delete_if
, you can remove non-string elements:
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."]
Or as Arupt Rakshit commented, you can use Array#select!
or Array#keep_if
:
a.select! { |x| x.is_a? String }
a.keep_if { |x| x.is_a? String }
Upvotes: 1
Reputation: 118299
This is a correct example to use Enumerable#grep
:
Returns an array of every element in enum for which
Pattern === element
. If the optional block is supplied, each matching element is passed to it, and the block’s result is stored in the output 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."]
Upvotes: 3