Ruby: Defining methods

Ruby 3.2.5p208 (2024-07-26 revision 31d0f1a2e7dbfb60731d1f05b868e1d578cda493)

Data Structures | Functions
Defining methods

## Data Structures
struct | rb_scan_args_t

## Functions
void | rb_define_method_id (VALUE klass, ID mid, VALUE(*func)(ANYARGS), int argc)
| Identical to rb_define_method(), except it takes the name of the method in ID instead of C's string.
void | rb_define_method (VALUE klass, const char *mid, VALUE(*func)(ANYARGS), int arity)
| Defines a method.
void | rb_define_protected_method (VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
| Identical to rb_define_method(), except it defines a protected method.
void | rb_define_private_method (VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
| Identical to rb_define_method(), except it defines a private method.
void | rb_undef_method (VALUE klass, const char *name)
| Defines an undef of a method.
static enum rb_id_table_iterator_result | undef_method_i (ID name, VALUE value, void *data)
void | rb_undef_methods_from (VALUE klass, VALUE super)
void | rb_define_singleton_method (VALUE obj, const char *name, VALUE(*func)(ANYARGS), int argc)
| Identical to rb_define_method(), except it defines a singleton method.
void | rb_define_module_function (VALUE klass, const char *mid, VALUE(*func)(ANYARGS), int arity)
| Defines a module function for a module.
void | rb_define_global_function (const char *mid, VALUE(*func)(ANYARGS), int arity)
| Defines a global function.
void | rb_define_alias (VALUE klass, const char *dst, const char *src)
| Defines an alias of a method.
void | rb_define_attr (VALUE klass, const char *name, int read, int write)
| Defines public accessor method(s) for an attribute.
VALUE | rb_keyword_error_new (const char *error, VALUE keys)
static void | rb_keyword_error (const char *error, VALUE keys)
static void | unknown_keyword_error (VALUE hash, const ID *table, int keywords)
static int | separate_symbol (st_data_t key, st_data_t value, st_data_t arg)
VALUE | rb_extract_keywords (VALUE *orighash)
| Splits a hash into two.
int | rb_get_kwargs (VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
| Keyword argument deconstructor.
static void | rb_scan_args_parse (int kw_flag, const char *fmt, struct rb_scan_args_t *arg)
static int | rb_scan_args_assign (const struct rb_scan_args_t *arg, int argc, const VALUE *const argv, va_list vargs)
static int | rb_scan_args_result (const struct rb_scan_args_t *const arg, int argc)
int | rb_scan_args (int argc, const VALUE *argv, const char *fmt,...)
| Retrieves argument from argc and argv to given VALUE references according to the format string.
int | rb_scan_args_kw (int kw_flag, int argc, const VALUE *argv, const char *fmt,...)
| Identical to rb_scan_args(), except it also accepts `kw_splat`.
int | rb_keyword_given_p (void)
| Determines if the current method is given a keyword argument.
int | rb_block_given_p (void)
| Determines if the current method is given a block.
void | rb_need_block (void)
| Declares that the current method needs a block.

## Detailed Description

There are some APIs to define a method from C. These API takes a C function as a method body.

### Method body functions

Method body functions must return a VALUE and can be one of the following form:

#### Fixed number of parameters

This form is a normal C function, excepting it takes a receiver object as the first argument.

static VALUE my_method(VALUE self, VALUE x, VALUE y);
VALUE
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40

#### argc and argv style

This form takes three parameters: argc, argv and self. self is the receiver. argc is the number of arguments. argv is a pointer to an array of the arguments.

static VALUE my_method(int argc, VALUE *argv, VALUE self);

#### Ruby array style

This form takes two parameters: self and args. self is the receiver. args is an Array object which contains the arguments.

static VALUE my_method(VALUE self, VALUE args);

### Number of parameters

Method defining APIs takes the number of parameters which the method will takes. This number is called argc. argc can be:

- Zero or positive number. This means the method body function takes a fixed number of parameters.
- `-1`. This means the method body function is "argc and argv" style.
- `-2`. This means the method body function is "self and args" style.

## Function Documentation

## ◆ rb_block_given_p()

int rb_block_given_p | ( | void |  | ) |

Determines if the current method is given a block.

Return values

  false | No block is given.
  true | A block is given.

Definition at line 868 of file eval.c.

Referenced by rb_ary_delete(), rb_ary_sort_bang(), rb_method_call(), rb_method_call_kw(), and rb_need_block().

## ◆ rb_define_alias()

void rb_define_alias | ( | VALUE | klass,
|  | const char * | dst,
|  | const char * | src )

Defines an alias of a method.

Parameters

  [in,out] | klass | The class which the original method belongs to; this is also where the new method will belong to.
  [in] | dst | A new name for the method.
  [in] | src | The original name of the method.

Exceptions

  rb_eTypeError | `klass` is a non-module.
  rb_eFrozenError | `klass` is frozen.
  rb_eNameError | There is no such method named as `src` in `klass`.

Definition at line 2289 of file class.c.

## ◆ rb_define_attr()

void rb_define_attr | ( | VALUE | klass,
|  | const char * | name,
|  | int | read,
|  | int | write )

Defines public accessor method(s) for an attribute.

Parameters

  [out] | klass | The class which the attribute will belong to.
  [in] | name | Name of the attribute.
  [in] | read | Whether to define a getter method.
  [in] | write | Whether to define a setter method.

Exceptions

  rb_eTypeError | `klass` is a non-module.
  rb_eFrozenError | `klass` is frozen.
  rb_eNameError | `name` invalid as an attr e.g. an operator.

Definition at line 2295 of file class.c.

## ◆ rb_define_global_function()

void rb_define_global_function | ( | const char * | mid,
|  | VALUE(* | func )(ANYARGS),
|  | int | arity )

Defines a global function.

Parameters

  [in] | mid | Name of the function.
  [in] | func | The method body.
  [in] | arity | The number of parameters. See Defining methods.

Note
  There are in fact 18 different prototypes for func.

See also
  ruby::backward::cxxanyargs::define_method::rb_define_global_function

Definition at line 2283 of file class.c.

## ◆ rb_define_method()

void rb_define_method | ( | VALUE | klass,
|  | const char * | mid,
|  | VALUE(* | func )(ANYARGS),
|  | int | arity )

Defines a method.

Parameters

  [out] | klass | A module or a class.
  [in] | mid | Name of the function.
  [in] | func | The method body.
  [in] | arity | The number of parameters. See Defining methods.

Note
  There are in fact 18 different prototypes for func.

See also
  ruby::backward::cxxanyargs::define_method::rb_define_method

Definition at line 2089 of file class.c.

## ◆ rb_define_method_id()

void rb_define_method_id | ( | VALUE | klass,
|  | ID | mid,
|  | VALUE(* | func )(ANYARGS),
|  | int | arity )

Identical to rb_define_method(), except it takes the name of the method in ID instead of C's string.

Parameters

  [out] | klass | A module or a class.
  [in] | mid | Name of the function.
  [in] | func | The method body.
  [in] | arity | The number of parameters. See Defining methods.

Note
  There are in fact 18 different prototypes for func.

See also
  ruby::backward::cxxanyargs::define_method::rb_define_method_id

Definition at line 2080 of file class.c.

## ◆ rb_define_module_function()

void rb_define_module_function | ( | VALUE | klass,
|  | const char * | mid,
|  | VALUE(* | func )(ANYARGS),
|  | int | arity )

Defines a module function for a module.

Parameters

  [out] | klass | A module or a class.
  [in] | mid | Name of the function.
  [in] | func | The method body.
  [in] | arity | The number of parameters. See Defining methods.

Note
  There are in fact 18 different prototypes for func.

See also
  ruby::backward::cxxanyargs::define_method::rb_define_module_function

Definition at line 2273 of file class.c.

## ◆ rb_define_private_method()

void rb_define_private_method | ( | VALUE | klass,
|  | const char * | mid,
|  | VALUE(* | func )(ANYARGS),
|  | int | arity )

Identical to rb_define_method(), except it defines a private method.

Parameters

  [out] | klass | A module or a class.
  [in] | mid | Name of the function.
  [in] | func | The method body.
  [in] | arity | The number of parameters. See Defining methods.

Note
  There are in fact 18 different prototypes for func.

See also
  ruby::backward::cxxanyargs::define_method::rb_define_protected_method

Definition at line 2107 of file class.c.

## ◆ rb_define_protected_method()

void rb_define_protected_method | ( | VALUE | klass,
|  | const char * | mid,
|  | VALUE(* | func )(ANYARGS),
|  | int | arity )

Identical to rb_define_method(), except it defines a protected method.

Parameters

  [out] | klass | A module or a class.
  [in] | mid | Name of the function.
  [in] | func | The method body.
  [in] | arity | The number of parameters. See Defining methods.

Note
  There are in fact 18 different prototypes for func.

See also
  ruby::backward::cxxanyargs::define_method::rb_define_protected_method

Definition at line 2098 of file class.c.

## ◆ rb_define_singleton_method()

void rb_define_singleton_method | ( | VALUE | obj,
|  | const char * | mid,
|  | VALUE(* | func )(ANYARGS),
|  | int | arity )

Identical to rb_define_method(), except it defines a singleton method.

Parameters

  [out] | obj | Arbitrary ruby object.
  [in] | mid | Name of the function.
  [in] | func | The method body.
  [in] | arity | The number of parameters. See Defining methods.

Note
  There are in fact 18 different prototypes for func.

See also
  ruby::backward::cxxanyargs::define_method::rb_define_singleton_method

Definition at line 2264 of file class.c.

## ◆ rb_extract_keywords()

VALUE rb_extract_keywords | ( | VALUE * | orighash | ) |

Splits a hash into two.

Takes a hash of various keys, and split it into symbol-keyed parts and others. Symbol-keyed part becomes the return value. What remains are returned as a new hash object stored at the argument pointer.

Parameters

  [in,out] | orighash | Pointer to a target hash to split.

Returns
  An extracted keyword hash.

Postcondition
  Upon successful return `orighash` points to another hash object, whose contents are the remainder of the operation.

Note
  The argument hash object is not modified.

Definition at line 2350 of file class.c.

## ◆ rb_get_kwargs()

int rb_get_kwargs | ( | VALUE | keyword_hash,
|  | const ID * | table,
|  | int | required,
|  | int | optional,
|  | VALUE * | values )

Keyword argument deconstructor.

Retrieves argument values bound to keywords, which directed by `table` into `values`, deleting retrieved entries from `keyword_hash` along the way. First `required` number of IDs referred by `table` are mandatory, and succeeding `optional` (`-optional-1` if `optional` is negative) number of IDs are optional. If a mandatory key is not contained in `keyword_hash`, raises rb_eArgError. If an optional key is not present in `keyword_hash`, the corresponding element in `values` is set to RUBY_Qundef. If `optional` is negative, rest of `keyword_hash` are ignored, otherwise raises rb_eArgError.

Warning
  Handling keyword arguments in the C API is less efficient than handling them in Ruby. Consider using a Ruby wrapper method around a non-keyword C function.

See also
  https://bugs.ruby-lang.org/issues/11339

Parameters

  [out] | keyword_hash | Target hash to deconstruct.
  [in] | table | List of keywords that you are interested in.
  [in] | required | Number of mandatory keywords.
  [in] | optional | Number of optional keywords (can be negative).
  [out] | values | Buffer to be filled.

Exceptions

  rb_eArgError | Absence of a mandatory keyword.
  rb_eArgError | Found an unknown keyword.

Returns
  Number of found values that are stored into `values`.

Definition at line 2368 of file class.c.

## ◆ rb_keyword_error()

static void rb_keyword_error | ( | const char * | error,
|  | VALUE | keys )
| static

Definition at line 2321 of file class.c.

## ◆ rb_keyword_error_new()

VALUE rb_keyword_error_new | ( | const char * | error,
|  | VALUE | keys )

Definition at line 2301 of file class.c.

## ◆ rb_keyword_given_p()

int rb_keyword_given_p | ( | void |  | ) |

Determines if the current method is given a keyword argument.

Return values

  false | No keyword argument is given.
  true | Keyword argument(s) are given.

Definition at line 881 of file eval.c.

Referenced by rb_enumeratorize_with_size().

## ◆ rb_need_block()

void rb_need_block | ( | void |  | ) |

Declares that the current method needs a block.

Exceptions

  rb_eLocalJumpError | No block given.

Definition at line 889 of file eval.c.

## ◆ rb_scan_args()

int rb_scan_args | ( | int | argc,
|  | const VALUE * | argv,
|  | const char * | fmt,
|  |  | ... )

Retrieves argument from argc and argv to given VALUE references according to the format string.

The format can be described in ABNF as follows:

scan-arg-spec := param-arg-spec [keyword-arg-spec] [block-arg-spec]
param-arg-spec := pre-arg-spec [post-arg-spec] / post-arg-spec /
pre-opt-post-arg-spec
pre-arg-spec := num-of-leading-mandatory-args
[num-of-optional-args]
post-arg-spec := sym-for-variable-length-args
[num-of-trailing-mandatory-args]
pre-opt-post-arg-spec := num-of-leading-mandatory-args num-of-optional-args
num-of-trailing-mandatory-args
keyword-arg-spec := sym-for-keyword-arg
block-arg-spec := sym-for-block-arg
num-of-leading-mandatory-args := DIGIT ; The number of leading mandatory
; arguments
num-of-optional-args := DIGIT ; The number of optional arguments
sym-for-variable-length-args := "*" ; Indicates that variable length
; arguments are captured as a ruby
; array
num-of-trailing-mandatory-args := DIGIT ; The number of trailing mandatory
; arguments
sym-for-keyword-arg := ":" ; Indicates that keyword argument
; captured as a hash.
; If keyword arguments are not
; provided, returns nil.
sym-for-block-arg := "&" ; Indicates that an iterator block
; should be captured if given
ruby
The main namespace.
Definition cxxanyargs.hpp:37

For example, "12" means that the method requires at least one argument, and at most receives three (1+2) arguments. So, the format string must be followed by three variable references, which are to be assigned to captured arguments. For omitted arguments, variables are set to RUBY_Qnil. `NULL` can be put in place of a variable reference, which means the corresponding captured argument(s) should be just dropped.

The number of given arguments, excluding an option hash or iterator block, is returned.

Parameters

  [in] | argc | Length of `argv`.
  [in] | argv | Pointer to the arguments to parse.
  [in] | fmt | Format, in the language described above.
  [out] | ... | Variables to fill in.

Exceptions

  rb_eFatal | Malformed `fmt`.
  rb_eArgError | Arity mismatch.

Returns
  Actually parsed number of given arguments.

Postcondition
  Each values passed to `argv` is filled into the variadic arguments, according to the format.

Definition at line 2579 of file class.c.

Referenced by rb_f_trace_var(), rb_f_untrace_var(), and rb_obj_init_clone().

## ◆ rb_scan_args_assign()

static int rb_scan_args_assign | ( | const struct rb_scan_args_t * | arg,
|  | int | argc,
|  | const VALUE *const | argv,
|  | va_list | vargs )
| static

Definition at line 2471 of file class.c.

## ◆ rb_scan_args_kw()

int rb_scan_args_kw | ( | int | kw_splat,
|  | int | argc,
|  | const VALUE * | argv,
|  | const char * | fmt,
|  |  | ... )

Identical to rb_scan_args(), except it also accepts `kw_splat`.

Parameters

  [in] | kw_splat | How to understand the keyword arguments. RB_SCAN_ARGS_PASS_CALLED_KEYWORDS: Same behaviour as rb_scan_args(). RB_SCAN_ARGS_KEYWORDS: The final argument is a kwarg. RB_SCAN_ARGS_LAST_HASH_KEYWORDS: The final argument is a kwarg, iff it is a hash.
  [in] | argc | Length of `argv`.
  [in] | argv | Pointer to the arguments to parse.
  [in] | fmt | Format, in the language described above.
  [out] | ... | Variables to fill in.

Exceptions

  rb_eFatal | Malformed `fmt`.
  rb_eArgError | Arity mismatch.

Returns
  Actually parsed number of given arguments.

Postcondition
  Each values passed to `argv` is filled into the variadic arguments, according to the format.

Definition at line 2592 of file class.c.

## ◆ rb_scan_args_parse()

static void rb_scan_args_parse | ( | int | kw_flag,
|  | const char * | fmt,
|  | struct rb_scan_args_t * | arg )
| static

Definition at line 2434 of file class.c.

## ◆ rb_scan_args_result()

static int rb_scan_args_result | ( | const struct rb_scan_args_t *const | arg,
|  | int | argc )
| static

Definition at line 2560 of file class.c.

## ◆ rb_undef_method()

void rb_undef_method | ( | VALUE | klass,
|  | const char * | name )

Defines an undef of a method.

– What?

In ruby, there are two separate concepts called "undef" and "remove_method". The thing you imagine when you "un-define" a method is remove_method. This one on the other hand is masking of a previous method definition. Suppose for instance:

class Foo
def foo
end
end
class Bar < Foo
def bar
foo
end
end
class Baz < Foo
undef foo # <--- (*1)
end

This `undef foo` at `(*1)` must not eliminate `Foo#foo`, because that method is also used from `Bar#bar`. So instead of physically executing the target method, `undef` inserts a special filtering entry to the class (`Baz` this case). That entry, when called, acts as if there were no methods at all. But the original can still be accessible, via ways like `Bar#bar` above.

Parameters

  [out] | klass | The class to insert an undef.
  [in] | name | Name of the undef.

Exceptions

  rb_eTypeError | `klass` is a non-module.
  rb_eFrozenError | `klass` is frozen.

See also
  rb_remove_method

Definition at line 2113 of file class.c.

## ◆ rb_undef_methods_from()

void rb_undef_methods_from | ( | VALUE | klass,
|  | VALUE | super )

Definition at line 2127 of file class.c.

## ◆ separate_symbol()

static int separate_symbol | ( | st_data_t | key,
|  | st_data_t | value,
|  | st_data_t | arg )
| static

Definition at line 2340 of file class.c.

## ◆ undef_method_i()

static enum rb_id_table_iterator_result undef_method_i | ( | ID | name,
|  | VALUE | value,
|  | void * | data )
| static

Definition at line 2119 of file class.c.

## ◆ unknown_keyword_error()

static void unknown_keyword_error | ( | VALUE | hash,
|  | const ID * | table,
|  | int | keywords )
| static

Definition at line 2328 of file class.c.