Barber-Colony-2909
Barber-Colony-2909

Reputation: 51

In ruby, is there a way to know in the console what a method does?

In Ruby, if i am looking for the methods of a class. ie:String.methods.sort and i have the following:

[:!, :!=, :!~, :<, :<=, :<=>, :==, :===, :=~, :>, :>=, :__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,...]

Is there a way for me to type a command in the console to explore a method? If i am unfamiliar with :display and i want to know what it does, what it returns, is it possible?

If yes, does PHP and javascript have something similar to see method definition in console? It does not look like I have encountered it.

Upvotes: 1

Views: 290

Answers (2)

Simple Lime
Simple Lime

Reputation: 11035

You can use

help 'String#display'

and it'll show the rdoc for the method (the same output that would show from running ri 'String#display' outside of irb. You can also just type help into irb and it'll go into a mode where you can just keep typing method names and it'll show the rdoc (enter a blank line to exit).

Upvotes: 5

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

If you use Pry, it has a handy shortcut, 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;
}

Upvotes: 3

Related Questions