Is there any way to set a hash with values such as <
, >
, %
, +
, etc?
I want to create a method that accepts an array of ints, and a hash with parameters.
In the method below array
is the array to be filtered, and hash
is the parameters. The idea is that any number less than min
or more than max
is removed.
def range_filter(array, hash)
checker={min=> <, ,max => >} # this is NOT working code, this the line I am curious about
checker.each_key {|key| array.delete_if {|x| x checker[key] args[key] }
array.each{|num| puts num}
end
The desired results would be
array=[1, 25, 15, 7, 50]
filter={min=> 10, max=> 30}
range_filter(array, filter)
# => 25
# => 15
In ruby, even math is a method invocation. And math symbols can be stored as ruby symbols. These lines are identical:
1 + 2 # 3
1.+(2) # 3
1.send(:+, 2) # 3
So armed with that, storing it as a hash is simple:
op = { :method => :> }
puts 1.send(op[:method], 2) # false
puts 3.send(op[:method], 2) # true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With