如果获取索引,如果数组中的对象包含Ruby中的期望值

时间:2017-06-22 08:33:24

标签: ruby

所以这是我从某个地方得到的数组,我想获得包含" text"的对象的索引。 => "资产&#34 ;.我怎么能在Ruby中做到这一点?

示例

[{
                     "class" => "android.support.v7.widget.AppCompatTextView",
                       "tag" => nil,
               "description" => "android.support.v7.widget.AppCompatTextView{b777d8c V.ED..... ........ 0,39-355,168 #7f0e007f app:id/textview_sectiontitle}",
                        "id" => "textview_sectiontitle",
                      "text" => "Assets",
                   "visible" => true,
                      "rect" => {
              "height" => 129,
               "width" => 355,
                   "y" => 2088,
                   "x" => 80,
            "center_x" => 257,
            "center_y" => 2152
        },
                   "enabled" => true,
        "contentDescription" => nil
    },
    {
                     "class" => "android.support.v7.widget.AppCompatImageButton",
                       "tag" => nil,
               "description" => "android.support.v7.widget.AppCompatImageButton{ae57704 VFED..C.. ........ 1056,0-1280,208 #7f0e0109 app:id/imagebutton_amount}",
                        "id" => "imagebutton_amount",
                   "visible" => true,
                      "rect" => {
              "height" => 208,
               "width" => 224,
                   "y" => 2049,
                   "x" => 1136,
            "center_x" => 1248,
            "center_y" => 2153
        },
                   "enabled" => true,
        "contentDescription" => nil
    }]

2 个答案:

答案 0 :(得分:6)

试试这个

arr.index { |item| item["text"] == "Assets" }

答案 1 :(得分:0)

更像是手写的东西:

def lel a
  a.each do |x|
    puts(a.index(x)) if (x.has_key?'text' and x['text'].eql?'Assets')
  end
end

然后将数组传递给' lel'功能

lel a
 => 0
b = [a[1],a[0]]
.
.
.
lel b
 => 1