gpt4 book ai didi

ruby - Ruby 数学运算符可以存储在哈希中并在以后动态应用吗?

转载 作者:数据小太阳 更新时间:2023-10-29 07:24:04 24 4
gpt4 key购买 nike

有什么方法可以设置一个散列值,例如 < , > , % , + , ETC?我想创建一个接受整数数组和带参数的散列的方法。

在下面的方法中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

期望的结果是

array=[1, 25, 15, 7, 50]
filter={min=> 10, max=> 30}
range_filter(array, filter)
# => 25
# => 15

最佳答案

在 ruby​​ 中,即使是数学也是一种方法调用。数学符号可以存储为 ruby 符号。这些行是相同的:

1 + 2         # 3
1.+(2) # 3
1.send(:+, 2) # 3

有了它,将它存储为散列很简单:

op = { :method => :> }
puts 1.send(op[:method], 2) # false
puts 3.send(op[:method], 2) # true

关于ruby - Ruby 数学运算符可以存储在哈希中并在以后动态应用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8437497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com