有什么办法来设定值比如哈希值<,>,%,+,等?我想创建一个接受一个int数组的方法,以及一个带参数的哈希.
在下面的方法中array是要过滤的数组,并且hash是参数.这个想法是删除任何小于min或大于的数字max.
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
Run Code Online (Sandbox Code Playgroud)
期望的结果将是
array=[1, 25, 15, 7, 50]
filter={min=> 10, max=> 30}
range_filter(array, filter)
# => 25
# => 15
Run Code Online (Sandbox Code Playgroud)
当然,将它们存储为字符串(或符号)并使用 object.send(function_name, argument)
> operators = ["<", ">", "%", "+"]
=> ["<", ">", "%", "+"]
> operators.each{|op| puts [" 10 #{op} 3: ", 10.send(op,3)].join}
10 < 3: false
10 > 3: true
10 % 3: 1
10 + 3: 13
Run Code Online (Sandbox Code Playgroud)
在ruby中,即使数学也是一种方法调用.并且数学符号可以存储为ruby符号.这些行是相同的:
1 + 2 # 3
1.+(2) # 3
1.send(:+, 2) # 3
Run Code Online (Sandbox Code Playgroud)
如此武装,存储它很简单:
op = { :method => :> }
puts 1.send(op[:method], 2) # false
puts 3.send(op[:method], 2) # true
Run Code Online (Sandbox Code Playgroud)