gpt4 book ai didi

ruby - 比较 Procs 的内容,而不是结果

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

使用 Ruby 1.9.2

问题
比较两个过程的内容,而不是结果。我知道由于 halting problem 无法测试结果但没关系;反正我不想测试结果。

例如

proc {@x == "x"} == proc {@x == "x"}  => false # doh!

返回 false 因为 procs 中的对象不一样。

我笨拙的解决方案
我有一个解决方案,有点像我想要的,但它并没有真正测试过程是否与我放入的内容“相等”。在我的特定情况下,我的过程的格式将始终是对实例变量的 bool 测试,如下所示:

{@x == "x" && @y != "y" || @z == String} 

我写了一个动态构建类并创建实例变量设置为指定值的方法:

def create_proc_tester(property_value_hash)
new_class = Class.new.new

new_class.class.class_eval do
define_method(:xql?) { |&block| instance_eval &block }
end

property_value_hash.each do |key, value|
new_class.instance_variable_set("@#{key}", value)
end

new_class
end

可以这样使用:

class Foo
attr_accessor :block
end

foo = Foo.new
foo.block = proc {@x == "x" && @y != "y" || @z == String}

tester = create_proc_tester(:x => "x", :y => "y", :z => Fixnum)
puts "Test #1: #{tester.xql? &foo.block}"
tester = create_proc_tester(:x => "x", :y => "x", :z => String)
puts "Test #2: #{tester.xql? &foo.block}"

> Test #1: false
> Test #2: true

.
.
这一切都很棒,但我想知道是否有更好、更元的方法来实际测试 proc 的内容,而不仅仅是解决我的特定问题的解决方法;可以用来测试任何过程的东西。

我在想可能有一种方法可以使用 Ruby 解析器来比较一些东西,但我不知道如何做。我现在正在研究它,但我想我会试着看看这里是否有人以前做过这个并且知道怎么做。尽管由于 Ruby 的动态特性,这可能是一个死胡同,但这就是我现在正在寻找的地方。

最佳答案

如果您使用的是 Ruby 1.9,则可以使用 sourcify gem。

$ irb
> require 'sourcify'
=> true
> a = proc {@x == "x"}
=> #<Proc:0x9ba4240@(irb):2>
> b = proc {@x == %{x}}
=> #<Proc:0x9ba23f0@(irb):3>
> a == b
=> false
> a.to_source == b.to_source
=> true
> RUBY_VERSION
=> "1.9.2"

我们还遇到了 ParseTree/Ruby 1.9 incompatibility problem在我的公司。

关于ruby - 比较 Procs 的内容,而不是结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4404362/

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