简体   繁体   English

如何改善Ruby中的Array.select?

[英]How can I improve this Array.select in Ruby?

I just wrote this... horrible line of Ruby code, and I'm wondering if there isn't a better way of doing it. 我只是写了这行可怕的Ruby代码,我想知道是否还有更好的方法。

I have an array of hashes, of which I want to fetch one. 我有一系列哈希,我想取其中一个。 The "conditions" of what I want to select is in two separate arrays--one with keys and one with values. 我要选择的“条件”是在两个单独的数组中-一个带有键,另一个带有值。 If a hash in the array has the correct key == value for every pair in keys and values , I want to return that hash. 如果数组中的哈希对于keysvalues每对都具有正确的key == value values ,我想返回该哈希。

Any pointers to make the code more readable? 任何使代码更具可读性的指针?

arr = [
  {:foo => 'foo', :bar => 'bar', :baz => 'baz'},
  {:foo => 'bar', :bar => 'bar', :baz => 'bar'},
  {:foo => 'foo', :bar => 'foo', :baz => 'foo'},
]

keys = [:foo, :bar]
values  = ['foo', 'bar']

arr.select{|c| keys.map{|k| i = keys.index(k); c[keys[i]] == values[i]}.delete(false) != false}.first
# => {:foo => 'foo', :bar => 'bar', :baz => 'baz'}

Do you have to specify what you're looking for as an array of keys and an array of values? 您是否必须将要查找的内容指定为键数组和值数组? If you do, then convert them to a Hash like this: 如果这样做,则将它们转换为如下所示的哈希:

hsh = Hash[*keys.zip(values).flatten]  #=> {:foo=>"foo", :bar=>"bar"}

And then select like this: 然后选择这样:

arr.select { |c| c == c.merge(hsh) }   #=> [{:foo=>"foo", :bar=>"bar", :baz=>"baz"}]

If you can specify what you're looking for as a Hash in the first place, you don't need the first line. 如果您可以首先指定要作为哈希表的内容,则不需要第一行。

arr = [
  {foo:'foo', bar:'bar', baz:'baz'},
  {foo:'bar', bar:'bar', baz:'bar'},
  {foo:'foo', bar:'foo', baz:'foo'},
]

keys = [:foo, :bar]
values = ['foo', 'bar']

p arr.find { |c|
    keys.zip(values).all? { |k,v|
        c[k] == v
    }
}
  1. You can use {foo:'bar'} syntax to declare hashes if you have a symbol as key. 如果将符号作为键,则可以使用{foo:'bar'}语法声明哈希。
  2. Use Enumerable#find to find first occurence. 使用Enumerable#find查找首次出现。

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

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