【问题标题】:In ruby, is there a way to know in the console what a method does?在 ruby​​ 中,有没有办法在控制台中知道方法的作用?
【发布时间】:2018-08-08 13:54:32
【问题描述】:

在 Ruby 中,如果我正在寻找一个类的方法。 即:String.methods.sort 我有以下内容:

[:!, :!=, :!~, :<, :<=, :<=>, :==, :===, :=~, :>, :>=, :__id__,
:__send__, :allocate, :ancestors, :autoload, :autoload?, :class,
:class_eval, :class_exec, :class_variable_defined?,
:class_variable_get, :class_variable_set, :class_variables, :clone,
:const_defined?, :const_get, :const_missing, :const_set, :constants,
:define_singleton_method, :deprecate_constant, :display, :dup,
:enum_for, :eql?, :equal?, :extend, :freeze, :frozen?, :hash, 
:include, :include?, :included_modules, :inspect, :instance_eval,...]

有没有办法让我在控制台中键入命令来探索方法?如果我不熟悉:display 并且我想知道它的作用,它返回什么,有可能吗?

如果是,PHP 和 javascript 是否有类似的东西可以在控制台中查看方法定义?好像没遇到过。

【问题讨论】:

  • 参见this 对独立程序rirdoc 的讨论。
  • 非常感谢.. @CarySwoveland.. 你知道 php 和 Javascript 是否有类似的命令吗?这真的很方便,而不是总是在网上寻找文档。
  • 抱歉,我对这两种语言都不熟悉。也许其他人可以回答。
  • @Krishna JS 没有这个内置的。您必须参考文档。不确定 PHP。

标签: ruby class methods console


【解决方案1】:

你可以使用

help 'String#display'

它会显示该方法的 rdoc(与在 irb 之外运行 ri 'String#display' 时显示的输出相同。您也可以在 irb 中键入 help,它会进入一个模式,您可以只需继续输入方法名称,它就会显示 rdoc(输入空行退出)。

【讨论】:

  • 谢谢@Simple ...你有机会知道php和javascript是否有类似的命令吗?
【解决方案2】:

如果你使用Pry,它有一个方便的快捷方式,show-source

[1] pry(main)> show-source String.display

From: io.c (C Method):
Owner: Kernel
Visibility: public
Number of lines: 15

static VALUE
rb_obj_display(int argc, VALUE *argv, VALUE self)
{
    VALUE out;

    if (argc == 0) {
        out = rb_stdout;
    }
    else {
        rb_scan_args(argc, argv, "01", &out);
    }
    rb_io_write(out, self);

    return Qnil;
}

【讨论】:

  • 初学者如何理解一些Ruby方法的源代码?
  • @arjun:他就是这么问的。这是关于“方法做什么”的最终真相来源。更多“适合初学者”的解释/文档只需一次 google 搜索即可获得。
  • @SergioTulentsev .. 我不知道 Pry。非常感谢你提到它。我刚刚开始使用 Ruby,并且非常喜欢它。我遇到的其他问题之一是您是否知道 php 和 javascript 是否有类似的命令。请让我知道是否最好开始一个新线程。
  • @SergioTulentsev 嘿,如果人们开始阅读文档,StackOverflow 将是空的。 OP是初学者。你的回答对他来说可能是额外的知识。这可能只是顺便提及。 SimpleLine 上面写的就是 OP 正在寻找的答案。
  • @arjun:你怎么知道他在找什么?
猜你喜欢
  • 2010-12-24
  • 2015-05-14
  • 2016-02-23
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多