Compare the Content, Not the Results, of Procs

删除回忆录丶 提交于 2019-12-01 06:30:00

If you're using Ruby 1.9, you may be able to use the 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" 

We also ran into the ParseTree/Ruby 1.9 incompatibility problem at my company.

$ sudo gem install ruby2ruby ParseTree

require 'parse_tree'
require 'ruby2ruby'
require 'parse_tree_extensions'

# All of these are the same:
proc     { puts 'a'  }.to_ruby  # => "proc { puts(\"a\") }"
lambda   { puts "a"  }.to_ruby  # => "proc { puts(\"a\") }"
Proc.new { puts %{a} }.to_ruby  # => "proc { puts(\"a\") }"

# If you need to do this with classes:

class Bar; define_method(:foo) { 'a' }; end  

puts Ruby2Ruby.new.process(Unifier.new.process(ParseTree.translate(Bar)))

# will print this:
# class Bar < Object
#   def foo
#     "a"
#   end
# end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!