【问题标题】:Selecting index from array based on value根据值从数组中选择索引
【发布时间】:2018-02-08 13:17:48
【问题描述】:

我的 Ruby 代码如下所示:

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

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

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

我该怎么做?

【问题讨论】:

标签: arrays ruby select multidimensional-array indexing


【解决方案1】:

如果你看到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]

【讨论】:

  • 请注意,除了Array#each_index,还有其他选择,例如result = cols.size.times.select { ... }(0...cols.size).select { ... }0.upto(cols.size-1).select { ... }
【解决方案2】:

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

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]

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    相关资源
    最近更新 更多