Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Ruby math operators be stored in a hash and applied dynamically later?

Tags:

operators

ruby

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
like image 440
Btuman Avatar asked Dec 12 '22 07:12

Btuman


1 Answers

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
like image 174
Alex Wayne Avatar answered Feb 08 '23 23:02

Alex Wayne