, , select Array .
select , . , , , .
:
arr = [ 4, 8, 15, 16, 23, 42 ]
result = arr.select { |element| element > 20 }
puts result
, , , . :
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
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 , ..