加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

输出ruby方法的来源

发布时间:2020-12-17 03:39:11 所属栏目:百科 来源:网络整理
导读:假设我用一个方法创建一个类. class A def test puts 'test' endend 我想知道测试里面发生了什么.我想按字面输出: def test puts 'test'end 有没有办法在字符串中输出方法的来源? 解决方法 您可以使用 Pry查看方法 # myfile.rbrequire 'pry'class A def te
假设我用一个方法创建一个类.

class A
  def test
    puts 'test'
  end
end

我想知道测试里面发生了什么.我想按字面输出:

def test
  puts 'test'
end

有没有办法在字符串中输出方法的来源?

解决方法

您可以使用 Pry查看方法

# 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读