输出红宝石方法的来源 [英] Output the source of a ruby method
本文介绍了输出红宝石方法的来源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我在其中创建一个带有方法的类.
Say I make a class with a method in it.
class A
def test
puts 'test'
end
end
我想知道test
内部的情况.我想从字面上输出:
I want to know what goes on inside of test
. I want to literally output:
def test
puts 'test'
end
有没有办法以字符串形式输出方法的来源?
Is there any way to output the source of a method in a string?
推荐答案
您可以使用撬进行查看方法
You can use Pry to view methods
# myfile.rb
require 'pry'
class A
def test
return 'test'
end
end
puts Pry::Method(A.new.method(:test)).source #(1)
# or as suggested in the comments
puts Pry::Method.from_str("A#test").source #(2)
# uses less cpu cycles than #(1) because it does not call initialize - see comments
puts Pry::Method(A.allocate.method(:test)).source #(3)
# does not use memory to allocate class as #(1) and #(3) do
puts Pry::Method(A.instance_method(:test)).source #(4)
然后运行ruby myfile.rb
,您将看到:
def test
return 'test'
end
这篇关于输出红宝石方法的来源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文