Find_all in an array that matches the condition?

I have an array of hash entries and you want to filter based on the parameter passed to the function.

If there are three hash values A, Band CI want to do something like:

data = [{A:'a1', B:'b1', C:'c1'}, 
    {A:'a1', B:'b2', C:'c1'},
    {A:'a1', B:'b2', C:'c2'}, 
    {A:'a2', B:'b1', C:'c1'},
    {A:'a2', B:'b2', C:'c1'}]

data.find_all{ |d| d[:A].include?params[:A] }
    .find_all{ |d| d[:B].include?params[:B] }
    .find_all{ |d| d[:C].include?params[:C] }

find everything where A == 'a1' AND B = 'b2'

so for above I get: {A: 'a1', B: 'b2', C: 'c1'} and {A: 'a1', B: 'b2', C: 'c2'} * put the expressions if/ else, for example params.has_key? 'B', then do something. * change my code every time a new type of value is added to the Hash map (say, now I have D).

Note. The hash key is a character, but the value is a string, and I want to make "contains", not "equal".

SQL Select '=='

+4
2

, , select Array .

select , . , , , .

:

arr = [ 4, 8, 15, 16, 23, 42 ]
result = arr.select { |element| element > 20 }
puts result   # prints out [23, 42]

, , , . :

data = [{A:'a1', B:'b1', C:'c1'}, 
        {A:'a1', B:'b2', C:'c1'},
        {A:'a1', B:'b2', C:'c2'}, 
        {A:'a2', B:'b1', C:'c1'},
        {A:'a2', B:'b2', C:'c1'}]

, , - : , :A :B .

, , :A == 'a1' :B == 'b2'. :

data.select { |hash_element| hash_element[:A] == 'a1' && hash_element[:B] == 'b2' }

, , , , :A == 'a1' :B == 'b2'. , !

select :

http://www.ruby-doc.org/core-2.1.0/Array.html#method-i-select

-

if/else ... , select, , , , , . : true, . .

, , , select. , - :

def condition_test(hash_element, key_values)
    result = true
    key_values.each do |pair|
      if hash_element[pair[:key]] != pair[:value]
        result = false
      end
    end
    return result
end

# An example of the key-value pairs you might require to satisfy your select condition.
requirements = [ {:key => :A, :value => 'a1'},
                 {:key => :B, :value => 'b2'} ]

data.select { |hash_element| condition_test(hash_element, requirements) }

, :A == 'a1' :B == 'b2', . requirements , . condition_test, , , , - . if/else condition_test , ..

+13

Source: https://habr.com/ru/post/1525339/


All Articles