我有一个我想要搜索的哈希数组,我想编写一个方法,将选项哈希作为参数,并返回数组中所有动态匹配所有键/值对的元素,而且我很难搞清楚。
my_array = [
{
foo: 'a',
bar: 'b',
baz: 'c'
},
{
foo: 1,
bar: 2,
baz: 3
},
{
foo: 'A',
bar: 'B',
baz: 'C'
},
{
foo: 11,
bar: 12,
baz: 13
}
]
# takes an opts hash and returns all elements for which all
# all key/value pairs match
def search_by(opts)
opts.each do |k, v|
self.select { |f| f[k] == f[v] }
end
end
my_array.search_by(foo: 'a', bar: 'b')
# should return { foo: 'a', bar: 'b', baz: 'c' }
我已经尝试了几种不同的方法来动态组合一个块以根据SO上的类似问题传递给#select,但我没有太多的运气和避风港能够找到这个确切的用例。什么是动态#select与多个条件的最佳方式,而只需要执行#select一次?
答案 0 :(得分:1)
您可以使用Hash#>=
:
如果其他是哈希的子集或等于哈希,则返回
true
。
my_array.select { |h| h >= finder }
#=> [{:foo=>"a", :bar=>"b", :baz=>"c"}]
答案 1 :(得分:0)
你可能试图使这个过于复杂化。这个怎么样
function areSimilar(a, b) {
var isSimilar = true
var isAlreadySwap = false
a.forEach(function(item, index){
if(item !== b[index] && item === b[index+1] && !isAlreadySwap){
var temp = b[index]
b[index] = b[index+1]
b[index+1] = temp
isAlreadySwap = true
}else if(item !== b[index]){
isSimilar = false;
return;
}
})
return isSimilar
}
class foo():
def __init__(self):
some_instance_vars = 42
self.a()
def a(self):
manipulate(self.some_instance_vars)
do_io()
self.b()
def b(self):
manipulate_again(self.some_instance_vars)
do_io()
self.c()
def c(self):
manipulate_more(self.some_instance_vars)
do_io()
self.a()
foo = Foo()
使用给定的键返回适当的值,在您的情况下,这些值应匹配“finder”my_array = [
{foo: 'a', bar: 'b', baz: 'c'},
{foo: 1, bar: 2, baz: 3},
{foo: 'A', bar: 'B', baz: 'C'},
{foo: 11, bar: 12, baz: 13}
]
finder = {foo: 'a', bar: 'b'}
my_array.select {|h| h.values_at(*finder.keys) == finder.values }
#=> [{:foo=>"a", :bar=>"b", :baz=>"c"}]
中这些键的值。
为了使其明确按照您解释的方式工作,我们可以为Hash#values_at
定义单例方法:
Hash