繁体   English   中英

根据值从数组中选择索引

[英]Selecting index from array based on value

我有看起来像这样的Ruby代码:

  a = widgets["results"]["cols"].each_with_index.select do |v, i| 
    v["type"] == "string"
  end  

我只想获取v["type"]为“ string”的任何值的索引。 外部的“结果”数组具有大约10个值(内部的“ cols”数组具有两个值-其中一个的索引为“类型”); 我期望在这样的数组中返回两个结果: [7, 8] 但是,我得到这样的结果:

[[{"element"=>"processed", "type"=>"string"}, 7], [{"element"=>"settled", "type"=>"string"}, 8]]

我怎样才能做到这一点?

如果看到cols.each_with_index.to_a

[[{:element=>"processed", :type=>"string"}, 0], [{:element=>"processed", :type=>"number"}, 1], ...]

将给您数组中的每个哈希作为第一个值,将第二个哈希作为索引。 如果select难以返回索引,则该数组返回一个包含枚举的所有元素的数组,给定的块将为其返回true

但是您也可以尝试each_index ,它传递元素的索引而不是元素本身 ,因此它只会给您索引,例如[0,1,2,4]

这样,您可以通过访问cols哈希中的每个元素的索引并检查type键的值来应用验证,例如:

widgets = {
  results:  {
    cols: [
      { element: 'processed', type: 'string' },
      { element: 'processed', type: 'number' },
      { element: 'processed', type: 'string' } 
    ]
  }
}

cols = widgets[:results][:cols]
result = cols.each_index.select { |index| cols[index][:type] == 'string' }

p result
# [0, 2]

您可以使用数组注入方法以最少的行数获得预期的输出,并且代码如下所示,

cols = [{'type' => 'string'}, {'type' => 'not_string'}, {'type' => 'string'}]
cols.each_with_index.inject([]) do |idxs, (v, i)|
  idxs << i if v['type'] == 'string'
  idxs
end

输出如下

=> [0, 2]

您可以根据需要更改代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM