Ruby 数学运算符可以存储在哈希中并在以后动态应用吗?
有什么方法可以设置诸如 <
、>
、%
、+
等值的哈希值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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 Ruby 中,甚至数学也是方法调用。数学符号可以存储为 ruby 符号。这些行是相同的:
因此,有了这些,将其存储为散列就很简单了:
In ruby, even math is a method invocation. And math symbols can be stored as ruby symbols. These lines are identical:
So armed with that, storing it as a hash is simple:
当然,将它们存储为字符串(或符号)并使用
object.send(function_name, argument)
sure, store them as strings (or symbols) and use
object.send(function_name, argument)
这应该像预期的那样工作:
只需使用
Symbol
而不是普通运算符。这些运算符是数字对象的特殊方法,因此您只需使用send
及其等效的Symbol
即可动态调用它们。This should work just like expected:
Just use
Symbol
s instead of the plain operators. The operators are special methods of number objects so you can just usesend
and theirSymbol
equivalent to call them dynamically.在这种情况下,猜测使用符号不会增加可读性。试试这个:
更新
比较(它也有效,但如果你想要
lambda{ |x| x % 3 == 1 }
呢?)Guess using symbols doesn't add readability in this case. Try this:
Update
Compare with (it works too, but what if you wanted
lambda{ |x| x % 3 == 1 }
?)