Module: Kernel

Defined in:
mruby/mrblib/kernel.rb,
mruby/src/kernel.c,
mruby/mrblib/00kernel.rb,
mruby/mrbgems/mruby-print/mrblib/print.rb,
mruby/mrbgems/mruby-method/mrblib/kernel.rb,
mruby/mrbgems/mruby-object-ext/mrblib/object.rb,
mruby/mrbgems/mruby-enumerator/mrblib/enumerator.rb

Overview

Kernel

ISO 15.3.1

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.Array(arg) ⇒ Array

Returns arg as an Array using to_a method.

Array(1..5)   #=> [1, 2, 3, 4, 5]

Returns:



228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'mruby/mrbgems/mruby-kernel-ext/src/kernel.c', line 228

static mrb_value
mrb_f_array(mrb_state *mrb, mrb_value self)
{
  mrb_value arg = mrb_get_arg1(mrb);
  mrb_value tmp;

  tmp = mrb_type_convert_check(mrb, arg, MRB_TT_ARRAY, MRB_SYM(to_a));
  if (mrb_nil_p(tmp)) {
    return mrb_ary_new_from_values(mrb, 1, &arg);
  }

  return tmp;
}

.callerObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'mruby/mrbgems/mruby-kernel-ext/src/kernel.c', line 12

static mrb_value
mrb_f_caller(mrb_state *mrb, mrb_value self)
{
  mrb_value bt, v;
  mrb_int bt_len, argc, lev, n;

  argc = mrb_get_args(mrb, "|oi", &v, &n);

  bt = mrb_get_backtrace(mrb);
  bt_len = RARRAY_LEN(bt);

  switch (argc) {
  case 0:
    lev = 1;
    n = bt_len - 1;
    break;
  case 1:
    if (mrb_range_p(v)) {
      mrb_int beg, len;
      if (mrb_range_beg_len(mrb, v, &beg, &len, bt_len, TRUE) == MRB_RANGE_OK) {
        lev = beg;
        n = len;
      }
      else {
        return mrb_nil_value();
      }
    }
    else {
      lev = mrb_as_int(mrb, v);
      if (lev < 0) {
        mrb_raisef(mrb, E_ARGUMENT_ERROR, "negative level (%v)", v);
      }
      n = bt_len - lev;
    }
    break;
  case 2:
    lev = mrb_as_int(mrb, v);
    break;
  default:
    /* not reached */
    lev = n = 0;
    break;
  }
  if (lev >= bt_len) return mrb_nil_value();
  if (lev < 0) {
    mrb_raisef(mrb, E_ARGUMENT_ERROR, "negative level (%v)", v);
  }
  if (n < 0) {
    mrb_raisef(mrb, E_ARGUMENT_ERROR, "negative size (%d)", n);
  }
  if (n == 0 || bt_len <= lev) {
    return mrb_ary_new(mrb);
  }
  if (bt_len <= n + lev) n = bt_len - lev - 1;
  return mrb_ary_new_from_values(mrb, n, RARRAY_PTR(bt)+lev+1);
}

.raiseObject .raise(string) ⇒ Object .raise(exception[, string]) ⇒ Object

With no arguments, raises a RuntimeError With a single String argument, raises a RuntimeError with the string as a message. Otherwise, the first parameter should be the name of an Exception class (or an object that returns an Exception object when sent an exception message). The optional second parameter sets the message associated with the exception, and the third parameter is an array of callback information. Exceptions are caught by the rescue clause of begin...end blocks.

raise "Failed to create socket"
raise ArgumentError, "No parameters", caller


380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# File 'mruby/src/kernel.c', line 380

MRB_API mrb_value
mrb_f_raise(mrb_state *mrb, mrb_value self)
{
  mrb_value a[2], exc;
  mrb_int argc;

  argc = mrb_get_args(mrb, "|oo", &a[0], &a[1]);
  mrb->c->ci->mid = 0;
  switch (argc) {
  case 0:
    mrb_raise(mrb, E_RUNTIME_ERROR, "");
    break;
  case 1:
    if (mrb_string_p(a[0])) {
      a[1] = a[0];
      argc = 2;
      a[0] = mrb_obj_value(E_RUNTIME_ERROR);
    }
    /* fall through */
  default:
    exc = mrb_make_exception(mrb, argc, a);
    mrb_exc_raise(mrb, exc);
    break;
  }
  return mrb_nil_value();            /* not reached */
}

.Float(arg) ⇒ Float

Returns arg converted to a float. Numeric types are converted directly, the rest are converted using arg.to_f.

Float(1)           #=> 1.0
Float(123.456)     #=> 123.456
Float("123.456")   #=> 123.456
Float(nil)         #=> TypeError

Returns:



186
187
188
189
190
191
192
193
194
195
# File 'mruby/mrbgems/mruby-kernel-ext/src/kernel.c', line 186

static mrb_value
mrb_f_float(mrb_state *mrb, mrb_value self)
{
  mrb_value arg = mrb_get_arg1(mrb);

  if (mrb_string_p(arg)) {
    return mrb_float_value(mrb, mrb_str_to_dbl(mrb, arg, TRUE));
  }
  return mrb_ensure_float_type(mrb, arg);
}

.Hash(arg) ⇒ Hash

Returns a Hash if arg is a Hash. Returns an empty Hash when arg is nil or [].

Hash([])          #=> {}
Hash(nil)         #=> {}
Hash(key: :value) #=> {:key => :value}
Hash([1, 2, 3])   #=> TypeError

Returns:



256
257
258
259
260
261
262
263
264
265
266
# File 'mruby/mrbgems/mruby-kernel-ext/src/kernel.c', line 256

static mrb_value
mrb_f_hash(mrb_state *mrb, mrb_value self)
{
  mrb_value arg = mrb_get_arg1(mrb);

  if (mrb_nil_p(arg) || (mrb_array_p(arg) && RARRAY_LEN(arg) == 0)) {
    return mrb_hash_new(mrb);
  }
  mrb_ensure_hash_type(mrb, arg);
  return arg;
}

.Integer(arg, base = 0) ⇒ Integer

Converts arg to a Integer. Numeric types are converted directly (with floating-point numbers being truncated). base (0, or between 2 and 36) is a base for integer string representation. If arg is a String, when base is omitted or equals to zero, radix indicators (0, 0b, and 0x) are honored. In any case, strings should be strictly conformed to numeric representation. This behavior is different from that of String#to_i. Non string values will be treated as integers. Passing nil raises a TypeError.

Integer(123.999)    #=> 123
Integer("0x1a")     #=> 26
Integer(Time.new)   #=> 1204973019
Integer("0930", 10) #=> 930
Integer("111", 2)   #=> 7
Integer(nil)        #=> TypeError

Returns:



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'mruby/mrbgems/mruby-kernel-ext/src/kernel.c', line 131

static mrb_value
mrb_f_integer(mrb_state *mrb, mrb_value self)
{
  mrb_value val, tmp;
  mrb_int base = 0;

  mrb_get_args(mrb, "o|i", &val, &base);
  if (mrb_nil_p(val)) {
    if (base != 0) goto arg_error;
    mrb_raise(mrb, E_TYPE_ERROR, "can't convert nil into Integer");
  }
  switch (mrb_type(val)) {
#ifndef MRB_NO_FLOAT
    case MRB_TT_FLOAT:
      if (base != 0) goto arg_error;
      return mrb_float_to_integer(mrb, val);
#endif

    case MRB_TT_INTEGER:
      if (base != 0) goto arg_error;
      return val;

    case MRB_TT_STRING:
    string_conv:
      return mrb_str_to_integer(mrb, val, base, TRUE);

    default:
      break;
  }
  if (base != 0) {
    tmp = mrb_obj_as_string(mrb, val);
    if (mrb_string_p(tmp)) {
      val = tmp;
      goto string_conv;
    }
arg_error:
    mrb_raise(mrb, E_ARGUMENT_ERROR, "base specified for non string value");
  }
  /* to raise TypeError */
  return mrb_ensure_integer_type(mrb, val);
}

.String(arg) ⇒ String

Returns arg as an String. converted using to_s method.

String(self)        #=> "main"
String(self.class)  #=> "Object"
String(123456)      #=> "123456"

Returns:



209
210
211
212
213
214
215
216
217
# File 'mruby/mrbgems/mruby-kernel-ext/src/kernel.c', line 209

static mrb_value
mrb_f_string(mrb_state *mrb, mrb_value self)
{
  mrb_value arg = mrb_get_arg1(mrb);
  mrb_value tmp;

  tmp = mrb_type_convert(mrb, arg, MRB_TT_STRING, MRB_SYM(to_s));
  return tmp;
}

Instance Method Details

#!~(y) ⇒ Object

11.4.4 Step c)



38
39
40
# File 'mruby/mrblib/kernel.rb', line 38

def !~(y)
  !(self =~ y)
end

#<=>Object

15.3.1.3.2



81
82
83
84
85
86
87
88
89
# File 'mruby/src/kernel.c', line 81

static mrb_value
mrb_cmp_m(mrb_state *mrb, mrb_value self)
{
  mrb_value arg = mrb_get_arg1(mrb);

  if (mrb_equal(mrb, self, arg))
    return mrb_fixnum_value(0);
  return mrb_nil_value();
}

#===(other) ⇒ Boolean

Case Equality—For class Object, effectively the same as calling #==, but typically overridden by descendants to provide meaningful semantics in case statements.

Returns:

  • (Boolean)


73
74
75
76
77
78
79
# File 'mruby/src/kernel.c', line 73

static mrb_value
mrb_equal_m(mrb_state *mrb, mrb_value self)
{
  mrb_value arg = mrb_get_arg1(mrb);

  return mrb_bool_value(mrb_equal(mrb, self, arg));
}

#__callee__Object

Returns the called name of the current method as a Symbol. If called outside of a method, it returns nil.



98
99
100
101
102
103
104
105
106
107
# File 'mruby/mrbgems/mruby-kernel-ext/src/kernel.c', line 98

static mrb_value
mrb_f_callee(mrb_state *mrb, mrb_value self)
{
  mrb_callinfo *ci = mrb->c->ci;
  ci--;
  if (ci->mid)
    return mrb_symbol_value(ci->mid);
  else
    return mrb_nil_value();
}

#__case_eqqObject

internal



487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# File 'mruby/src/kernel.c', line 487

static mrb_value
mrb_obj_ceqq(mrb_state *mrb, mrb_value self)
{
  mrb_value v = mrb_get_arg1(mrb);
  mrb_int i, len;
  mrb_sym eqq = MRB_OPSYM(eqq);
  mrb_value ary;

  mrb->c->ci->mid = 0;
  if (mrb_array_p(self)) {
    ary = self;
  }
  else if (mrb_nil_p(self)) {
    return mrb_false_value();
  }
  else if (!mrb_respond_to(mrb, self, MRB_SYM(to_a))) {
    mrb_value c = mrb_funcall_argv(mrb, self, eqq, 1, &v);
    if (mrb_test(c)) return mrb_true_value();
    return mrb_false_value();
  }
  else {
    ary = mrb_funcall_id(mrb, self, MRB_SYM(to_a), 0);
    if (mrb_nil_p(ary)) {
      return mrb_funcall_argv(mrb, self, eqq, 1, &v);
    }
    mrb_ensure_array_type(mrb, ary);
  }
  len = RARRAY_LEN(ary);
  for (i=0; i<len; i++) {
    mrb_value c = mrb_funcall_argv(mrb, mrb_ary_entry(ary, i), eqq, 1, &v);
    if (mrb_test(c)) return mrb_true_value();
  }
  return mrb_false_value();
}

#__ENCODING__Object

internal



522
523
524
525
526
527
528
529
530
531
# File 'mruby/src/kernel.c', line 522

static mrb_value
mrb_encoding(mrb_state *mrb, mrb_value self)
{
  mrb_get_args(mrb, "");
#ifdef MRB_UTF8_STRING
  return mrb_str_new_lit(mrb, "UTF-8");
#else
  return mrb_str_new_lit(mrb, "ASCII-8BIT");
#endif
}

#__method__Object

Returns the called name of the current method as a Symbol. If called outside of a method, it returns nil.



77
78
79
80
81
82
83
84
85
86
87
88
# File 'mruby/mrbgems/mruby-kernel-ext/src/kernel.c', line 77

static mrb_value
mrb_f_method(mrb_state *mrb, mrb_value self)
{
  mrb_callinfo *ci = mrb->c->ci;
  ci--;
  if (ci->proc && ci->proc->e.env && ci->proc->e.env->tt == MRB_TT_ENV && ci->proc->e.env->mid)
    return mrb_symbol_value(ci->proc->e.env->mid);
  else if (ci->mid)
    return mrb_symbol_value(ci->mid);
  else
    return mrb_nil_value();
}

#__to_intObject

internal

#_inspect(_recur_list) ⇒ Object

internal method for inspect



43
44
45
# File 'mruby/mrblib/kernel.rb', line 43

def _inspect(_recur_list)
  self.inspect
end

#`(s) ⇒ Object

15.3.1.2.1 Kernel.‘ provided by Kernel#` 15.3.1.3.3



10
11
12
# File 'mruby/mrblib/kernel.rb', line 10

def `(s)
  raise NotImplementedError.new("backquotes not implemented")
end

#block_given?Boolean #iterator?Boolean

Returns true if yield would execute a block in the current context. The iterator? form is mildly deprecated.

def try
  if block_given?
    yield
  else
    "no block"
  end
end
try                  #=> "no block"
try { "hello" }      #=> "hello"
try do "hello" end   #=> "hello"

Overloads:

  • #block_given?Boolean

    Returns:

    • (Boolean)
  • #iterator?Boolean

    Returns:

    • (Boolean)


150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'mruby/src/kernel.c', line 150

static mrb_value
mrb_f_block_given_p_m(mrb_state *mrb, mrb_value self)
{
  mrb_callinfo *ci = &mrb->c->ci[-1];
  mrb_callinfo *cibase = mrb->c->cibase;
  mrb_value *bp;
  int bidx;
  struct REnv *e = NULL;
  const struct RProc *p;

  if (ci <= cibase) {
    /* toplevel does not have block */
    return mrb_false_value();
  }
  p = ci->proc;
  /* search method/class/module proc */
  while (p) {
    if (MRB_PROC_SCOPE_P(p)) break;
    e = MRB_PROC_ENV(p);
    p = p->upper;
  }
  if (p == NULL) return mrb_false_value();
  if (e) {
    bidx = env_bidx(e);
    if (bidx < 0) return mrb_false_value();
    bp = &e->stack[bidx];
    goto block_given;
  }
  /* search ci corresponding to proc */
  while (cibase < ci) {
    if (ci->proc == p) break;
    ci--;
  }
  if (ci == cibase) {
    /* proc is closure */
    if (!MRB_PROC_ENV_P(p)) return mrb_false_value();
    e = MRB_PROC_ENV(p);
    bidx = env_bidx(e);
    if (bidx < 0) return mrb_false_value();
    bp = &e->stack[bidx];
  }
  else if ((e = mrb_vm_ci_env(ci)) != NULL) {
    /* top-level does not have block slot (always false) */
    if (e->stack == mrb->c->stbase) return mrb_false_value();
    bidx = env_bidx(e);
    /* bidx may be useless (e.g. define_method) */
    if (bidx < 0) return mrb_false_value();
    bp = &e->stack[bidx];
  }
  else {
    uint8_t n = ci->n == 15 ? 1 : ci->n;
    uint8_t k = ci->nk == 15 ? 1 : ci->nk*2;
    bidx = n + k + 1;      /* self + args + kargs => bidx */
    bp = &ci->stack[bidx];
  }
 block_given:
  if (mrb_nil_p(*bp))
    return mrb_false_value();
  return mrb_true_value();
}

#classClass

Returns the class of obj. This method must always be called with an explicit receiver, as class is also a reserved word in Ruby.

1.class      #=> Integer
self.class   #=> Object

Returns:



223
224
225
226
227
# File 'mruby/src/kernel.c', line 223

static mrb_value
mrb_obj_class_m(mrb_state *mrb, mrb_value self)
{
  return mrb_obj_value(mrb_obj_class(mrb, self));
}

#cloneObject

Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. Copies the frozen state of obj. See also the discussion under Object#dup.

class Klass
   attr_accessor :str
end
s1 = Klass.new      #=> #<Klass:0x401b3a38>
s1.str = "Hello"    #=> "Hello"
s2 = s1.clone       #=> #<Klass:0x401b3998 @str="Hello">
s2.str[1,4] = "i"   #=> "i"
s1.inspect          #=> "#<Klass:0x401b3a38 @str=\"Hi\">"
s2.inspect          #=> "#<Klass:0x401b3998 @str=\"Hi\">"

This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.

Some Class(True False Nil Symbol Integer Float) Object cannot clone.

Returns:



2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
# File 'mruby/src/class.c', line 2811

MRB_API mrb_value
mrb_obj_clone(mrb_state *mrb, mrb_value self)
{
  struct RObject *p;
  mrb_value clone;

  if (mrb_immediate_p(self)) {
    return self;
  }
  if (mrb_sclass_p(self)) {
    mrb_raise(mrb, E_TYPE_ERROR, "can't clone singleton class");
  }
  p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self));
  p->c = mrb_singleton_class_clone(mrb, self);
  mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c);
  clone = mrb_obj_value(p);
  init_copy(mrb, clone, self);
  p->flags |= mrb_obj_ptr(self)->flags & MRB_FL_OBJ_IS_FROZEN;

  return clone;
}

#define_singleton_methodObject

15.3.1.3.45



373
374
375
376
377
# File 'mruby/mrbgems/mruby-metaprog/src/metaprog.c', line 373

static mrb_value
mod_define_singleton_method(mrb_state *mrb, mrb_value self)
{
  return mrb_mod_define_method_m(mrb, mrb_class_ptr(mrb_singleton_class(mrb, self)));
}

#dupObject

Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the frozen state of obj. See also the discussion under Object#clone. In general, clone and dup may have different semantics in descendant classes. While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendant object to create the new instance.

This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.

Returns:



2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
# File 'mruby/src/class.c', line 2852

MRB_API mrb_value
mrb_obj_dup(mrb_state *mrb, mrb_value obj)
{
  struct RBasic *p;
  mrb_value dup;

  if (mrb_immediate_p(obj)) {
    return obj;
  }
  if (mrb_sclass_p(obj)) {
    mrb_raise(mrb, E_TYPE_ERROR, "can't dup singleton class");
  }
  p = mrb_obj_alloc(mrb, mrb_type(obj), mrb_obj_class(mrb, obj));
  dup = mrb_obj_value(p);
  init_copy(mrb, dup, obj);

  return dup;
}

#==(other) ⇒ Boolean #equal?(other) ⇒ Boolean #eql?(other) ⇒ Boolean

Equality—At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning.

Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).

The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:

1 == 1.0     #=> true
1.eql? 1.0   #=> false

Overloads:

  • #==(other) ⇒ Boolean

    Returns:

    • (Boolean)
  • #equal?(other) ⇒ Boolean

    Returns:

    • (Boolean)
  • #eql?(other) ⇒ Boolean

    Returns:

    • (Boolean)


2093
2094
2095
2096
2097
2098
2099
# File 'mruby/src/class.c', line 2093

mrb_value
mrb_obj_equal_m(mrb_state *mrb, mrb_value self)
{
  mrb_value arg = mrb_get_arg1(mrb);

  return mrb_bool_value(mrb_obj_equal(mrb, self, arg));
}

#extend(*args) ⇒ Object

call-seq:

obj.extend(module, ...)    -> obj

Adds to obj the instance methods from each module given as a parameter.

module Mod
  def hello
    "Hello from Mod.\n"
  end
end

class Klass
  def hello
    "Hello from Klass.\n"
  end
end

k = Klass.new
k.hello         #=> "Hello from Klass.\n"
k.extend(Mod)   #=> #<Klass:0x401b3bc8>
k.hello         #=> "Hello from Mod.\n"

ISO 15.3.1.3.13



27
28
29
30
31
32
33
34
# File 'mruby/mrblib/00kernel.rb', line 27

def extend(*args)
  args.reverse!
  args.each do |m|
    m.extend_object(self)
    m.extended(self)
  end
  self
end

#freezeObject

15.3.1.3.10



229
230
231
232
233
234
235
236
237
238
239
240
# File 'mruby/src/kernel.c', line 229

MRB_API mrb_value
mrb_obj_freeze(mrb_state *mrb, mrb_value self)
{
  if (!mrb_immediate_p(self)) {
    struct RBasic *b = mrb_basic_ptr(self);
    if (!mrb_frozen_p(b)) {
      MRB_SET_FROZEN_FLAG(b);
      if (b->c->tt == MRB_TT_SCLASS) MRB_SET_FROZEN_FLAG(b->c);
    }
  }
  return self;
}

#frozen?Boolean

Returns:

  • (Boolean)


242
243
244
245
246
# File 'mruby/src/kernel.c', line 242

static mrb_value
mrb_obj_frozen(mrb_state *mrb, mrb_value self)
{
  return mrb_bool_value(mrb_immediate_p(self) || mrb_frozen_p(mrb_basic_ptr(self)));
}

#global_variablesArray

Returns an array of the names of global variables.

global_variables.grep /std/   #=> [:$stdin, :$stdout, :$stderr]

Returns:



981
982
983
984
985
986
987
988
989
# File 'mruby/src/variable.c', line 981

mrb_value
mrb_f_global_variables(mrb_state *mrb, mrb_value self)
{
  iv_tbl *t = mrb->globals;
  mrb_value ary = mrb_ary_new(mrb);

  iv_foreach(mrb, t, gv_i, &ary);
  return ary;
}

#hashInteger

Generates a Integer hash value for this object. This function must have the property that a.eql?(b) implies a.hash == b.hash. The hash value is used by class Hash. Any hash value that exceeds the capacity of a Integer will be truncated before being used.

Returns:



259
260
261
262
263
264
265
266
267
268
# File 'mruby/src/kernel.c', line 259

static mrb_value
mrb_obj_hash(mrb_state *mrb, mrb_value self)
{
#ifdef MRB_USE_BIGINT
  if (mrb_bigint_p(self)) {
    return mrb_bint_hash(mrb, self);
  }
#endif
  return mrb_int_value(mrb, mrb_obj_id(self));
}

#initialize_copyObject

15.3.1.3.16



271
272
273
274
275
276
277
278
279
280
281
# File 'mruby/src/kernel.c', line 271

mrb_value
mrb_obj_init_copy(mrb_state *mrb, mrb_value self)
{
  mrb_value orig = mrb_get_arg1(mrb);

  if (mrb_obj_equal(mrb, self, orig)) return self;
  if ((mrb_type(self) != mrb_type(orig)) || (mrb_obj_class(mrb, self) != mrb_obj_class(mrb, orig))) {
      mrb_raise(mrb, E_TYPE_ERROR, "initialize_copy should take same class object");
  }
  return self;
}

#inspectString

Returns a string containing a human-readable representation of obj. If not overridden and no instance variables, uses the to_s method to generate the string. obj. If not overridden, uses the to_s method to generate the string.

[ 1, 2, 3..4, 'five' ].inspect   #=> "[1, 2, 3..4, \"five\"]"
Time.new.inspect                 #=> "2008-03-08 19:43:39 +0900"

Returns:



55
56
57
58
59
60
61
62
# File 'mruby/src/kernel.c', line 55

MRB_API mrb_value
mrb_obj_inspect(mrb_state *mrb, mrb_value obj)
{
  if (mrb_object_p(obj) && mrb_obj_basic_to_s_p(mrb, obj)) {
    return mrb_obj_iv_inspect(mrb, mrb_obj_ptr(obj));
  }
  return mrb_any_to_s(mrb, obj);
}

#instance_of?Boolean

Returns true if obj is an instance of the given class. See also Object#kind_of?.

Returns:

  • (Boolean)


298
299
300
301
302
303
304
305
306
# File 'mruby/src/kernel.c', line 298

static mrb_value
obj_is_instance_of(mrb_state *mrb, mrb_value self)
{
  struct RClass *c;

  mrb_get_args(mrb, "c", &c);

  return mrb_bool_value(mrb_obj_is_instance_of(mrb, self, c));
}

#instance_variable_defined?(symbol) ⇒ Boolean

Returns true if the given instance variable is defined in obj.

class Fred
  def initialize(p1, p2)
    @a, @b = p1, p2
  end
end
fred = Fred.new('cat', 99)
fred.instance_variable_defined?(:@a)    #=> true
fred.instance_variable_defined?("@b")   #=> true
fred.instance_variable_defined?("@c")   #=> false

Returns:

  • (Boolean)


51
52
53
54
55
56
57
58
59
# File 'mruby/mrbgems/mruby-metaprog/src/metaprog.c', line 51

static mrb_value
mrb_obj_ivar_defined(mrb_state *mrb, mrb_value self)
{
  mrb_sym sym;

  mrb_get_args(mrb, "n", &sym);
  mrb_iv_name_sym_check(mrb, sym);
  return mrb_bool_value(mrb_iv_defined(mrb, self, sym));
}

#instance_variable_get(symbol) ⇒ Object

Returns the value of the given instance variable, or nil if the instance variable is not set. The @ part of the variable name should be included for regular instance variables. Throws a NameError exception if the supplied symbol is not valid as an instance variable name.

class Fred
  def initialize(p1, p2)
    @a, @b = p1, p2
  end
end
fred = Fred.new('cat', 99)
fred.instance_variable_get(:@a)    #=> "cat"
fred.instance_variable_get("@b")   #=> 99

Returns:



81
82
83
84
85
86
87
88
89
# File 'mruby/mrbgems/mruby-metaprog/src/metaprog.c', line 81

static mrb_value
mrb_obj_ivar_get(mrb_state *mrb, mrb_value self)
{
  mrb_sym iv_name;

  mrb_get_args(mrb, "n", &iv_name);
  mrb_iv_name_sym_check(mrb, iv_name);
  return mrb_iv_get(mrb, self, iv_name);
}

#instance_variable_set(symbol, obj) ⇒ Object

Sets the instance variable names by symbol to object, thereby frustrating the efforts of the class’s author to attempt to provide proper encapsulation. The variable did not have to exist prior to this call.

class Fred
  def initialize(p1, p2)
    @a, @b = p1, p2
  end
end
fred = Fred.new('cat', 99)
fred.instance_variable_set(:@a, 'dog')   #=> "dog"
fred.instance_variable_set(:@c, 'cat')   #=> "cat"
fred.inspect                             #=> "#<Fred:0x401b3da8 @a=\"dog\", @b=99, @c=\"cat\">"

Returns:



111
112
113
114
115
116
117
118
119
120
121
# File 'mruby/mrbgems/mruby-metaprog/src/metaprog.c', line 111

static mrb_value
mrb_obj_ivar_set(mrb_state *mrb, mrb_value self)
{
  mrb_sym iv_name;
  mrb_value val;

  mrb_get_args(mrb, "no", &iv_name, &val);
  mrb_iv_name_sym_check(mrb, iv_name);
  mrb_iv_set(mrb, self, iv_name, val);
  return val;
}

#instance_variablesArray

Returns an array of instance variable names for the receiver. Note that simply defining an accessor does not create the corresponding instance variable.

class Fred
  attr_accessor :a1
  def initialize
    @iv = 3
  end
end
Fred.new.instance_variables   #=> [:@iv]

Returns:



554
555
556
557
558
559
560
561
562
563
564
# File 'mruby/src/variable.c', line 554

mrb_value
mrb_obj_instance_variables(mrb_state *mrb, mrb_value self)
{
  mrb_value ary;

  ary = mrb_ary_new(mrb);
  if (obj_iv_p(self)) {
    iv_foreach(mrb, mrb_obj_ptr(self)->iv, iv_i, &ary);
  }
  return ary;
}

#is_a?Boolean #kind_of?Boolean

Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

module M;    end
class A
  include M
end
class B < A; end
class C < B; end
b = B.new
b.instance_of? A   #=> false
b.instance_of? B   #=> true
b.instance_of? C   #=> false
b.instance_of? M   #=> false
b.kind_of? A       #=> true
b.kind_of? B       #=> true
b.kind_of? C       #=> false
b.kind_of? M       #=> true

Overloads:

  • #is_a?Boolean

    Returns:

    • (Boolean)
  • #kind_of?Boolean

    Returns:

    • (Boolean)


335
336
337
338
339
340
341
342
343
# File 'mruby/src/kernel.c', line 335

static mrb_value
mrb_obj_is_kind_of_m(mrb_state *mrb, mrb_value self)
{
  struct RClass *c;

  mrb_get_args(mrb, "c", &c);

  return mrb_bool_value(mrb_obj_is_kind_of(mrb, self, c));
}

#block_given?Boolean #iterator?Boolean

Returns true if yield would execute a block in the current context. The iterator? form is mildly deprecated.

def try
  if block_given?
    yield
  else
    "no block"
  end
end
try                  #=> "no block"
try { "hello" }      #=> "hello"
try do "hello" end   #=> "hello"

Overloads:

  • #block_given?Boolean

    Returns:

    • (Boolean)
  • #iterator?Boolean

    Returns:

    • (Boolean)


150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'mruby/src/kernel.c', line 150

static mrb_value
mrb_f_block_given_p_m(mrb_state *mrb, mrb_value self)
{
  mrb_callinfo *ci = &mrb->c->ci[-1];
  mrb_callinfo *cibase = mrb->c->cibase;
  mrb_value *bp;
  int bidx;
  struct REnv *e = NULL;
  const struct RProc *p;

  if (ci <= cibase) {
    /* toplevel does not have block */
    return mrb_false_value();
  }
  p = ci->proc;
  /* search method/class/module proc */
  while (p) {
    if (MRB_PROC_SCOPE_P(p)) break;
    e = MRB_PROC_ENV(p);
    p = p->upper;
  }
  if (p == NULL) return mrb_false_value();
  if (e) {
    bidx = env_bidx(e);
    if (bidx < 0) return mrb_false_value();
    bp = &e->stack[bidx];
    goto block_given;
  }
  /* search ci corresponding to proc */
  while (cibase < ci) {
    if (ci->proc == p) break;
    ci--;
  }
  if (ci == cibase) {
    /* proc is closure */
    if (!MRB_PROC_ENV_P(p)) return mrb_false_value();
    e = MRB_PROC_ENV(p);
    bidx = env_bidx(e);
    if (bidx < 0) return mrb_false_value();
    bp = &e->stack[bidx];
  }
  else if ((e = mrb_vm_ci_env(ci)) != NULL) {
    /* top-level does not have block slot (always false) */
    if (e->stack == mrb->c->stbase) return mrb_false_value();
    bidx = env_bidx(e);
    /* bidx may be useless (e.g. define_method) */
    if (bidx < 0) return mrb_false_value();
    bp = &e->stack[bidx];
  }
  else {
    uint8_t n = ci->n == 15 ? 1 : ci->n;
    uint8_t k = ci->nk == 15 ? 1 : ci->nk*2;
    bidx = n + k + 1;      /* self + args + kargs => bidx */
    bp = &ci->stack[bidx];
  }
 block_given:
  if (mrb_nil_p(*bp))
    return mrb_false_value();
  return mrb_true_value();
}

#is_a?Boolean #kind_of?Boolean

Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

module M;    end
class A
  include M
end
class B < A; end
class C < B; end
b = B.new
b.instance_of? A   #=> false
b.instance_of? B   #=> true
b.instance_of? C   #=> false
b.instance_of? M   #=> false
b.kind_of? A       #=> true
b.kind_of? B       #=> true
b.kind_of? C       #=> false
b.kind_of? M       #=> true

Overloads:

  • #is_a?Boolean

    Returns:

    • (Boolean)
  • #kind_of?Boolean

    Returns:

    • (Boolean)


335
336
337
338
339
340
341
342
343
# File 'mruby/src/kernel.c', line 335

static mrb_value
mrb_obj_is_kind_of_m(mrb_state *mrb, mrb_value self)
{
  struct RClass *c;

  mrb_get_args(mrb, "c", &c);

  return mrb_bool_value(mrb_obj_is_kind_of(mrb, self, c));
}

#local_variablesArray

Returns the names of local variables in the current scope.

mruby limitation

If variable symbol information was stripped out from compiled binary files using ‘mruby-strip -l`, this method always returns an empty array.

Returns:



136
137
138
139
140
# File 'mruby/mrbgems/mruby-metaprog/src/metaprog.c', line 136

static mrb_value
mrb_local_variables(mrb_state *mrb, mrb_value self)
{
  return mrb_proc_local_variables(mrb, mrb->c->ci[-1].proc);
}

#loop(&block) ⇒ Object

Calls the given block repetitively.

ISO 15.3.1.3.29



27
28
29
30
31
32
33
34
35
# File 'mruby/mrblib/kernel.rb', line 27

def loop(&block)
  return to_enum :loop unless block

  while true
    yield
  end
rescue StopIteration => e
  e.result
end

#methodsArray

Returns a list of the names of methods publicly accessible in obj. This will include all the methods accessible in obj’s ancestors.

class Klass
  def kMethod()
  end
end
k = Klass.new
k.methods[0..9]    #=> [:kMethod, :respond_to?, :nil?, :is_a?,
                   #    :class, :instance_variable_set,
                   #    :methods, :extend, :__send__, :instance_eval]
k.methods.length   #=> 42

Returns:



237
238
239
240
241
242
243
# File 'mruby/mrbgems/mruby-metaprog/src/metaprog.c', line 237

static mrb_value
mrb_obj_methods_m(mrb_state *mrb, mrb_value self)
{
  mrb_bool recur = TRUE;
  mrb_get_args(mrb, "|b", &recur);
  return mrb_obj_methods(mrb, recur, self, (mrb_method_flag_t)0); /* everything but private */
}

#nil?Boolean

call_seq:

nil.nil?               -> true
<anything_else>.nil?   -> false

Only the object nil responds true to nil?.

Returns:

  • (Boolean)


353
354
355
356
357
# File 'mruby/src/kernel.c', line 353

static mrb_value
mrb_false(mrb_state *mrb, mrb_value self)
{
  return mrb_false_value();
}

#object_idObject

call-seq:

obj.__id__       -> int
obj.object_id    -> int

Returns an integer identifier for obj. The same number will be returned on all calls to id for a given object, and no two active objects will share an id. Object#object_id is a different concept from the :name notation, which returns the symbol id of name. Replaces the deprecated Object#id.



108
109
110
111
112
# File 'mruby/src/kernel.c', line 108

mrb_value
mrb_obj_id_m(mrb_state *mrb, mrb_value self)
{
  return mrb_fixnum_value(mrb_obj_id(self));
}

#p(*args) ⇒ Object

Print human readable object description

ISO 15.3.1.2.9 ISO 15.3.1.3.34



11
12
13
14
15
16
17
18
19
20
# File 'mruby/mrbgems/mruby-print/mrblib/print.rb', line 11

def p(*args)
  i = 0
  len = args.size
  while i < len
    __printstr__ args[i].inspect
    __printstr__ "\n"
    i += 1
  end
  args.__svalue
end

15.3.1.2.10 15.3.1.3.35



24
25
26
27
28
29
30
31
# File 'mruby/mrbgems/mruby-print/mrblib/print.rb', line 24

def print(*args)
  i = 0
  len = args.size
  while i < len
    __printstr__ args[i].to_s
    i += 1
  end
end

#printf(*args) ⇒ Object



52
53
54
# File 'mruby/mrbgems/mruby-print/mrblib/print.rb', line 52

def printf(*args)
  __printstr__(sprintf(*args))
end

#private_methods(all = true) ⇒ Array

Returns the list of private methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed.

Returns:



254
255
256
257
258
259
260
# File 'mruby/mrbgems/mruby-metaprog/src/metaprog.c', line 254

static mrb_value
mrb_obj_private_methods(mrb_state *mrb, mrb_value self)
{
  mrb_bool recur = TRUE;
  mrb_get_args(mrb, "|b", &recur);
  return mrb_obj_methods(mrb, recur, self, NOEX_PRIVATE); /* private attribute not define */
}

#protected_methods(all = true) ⇒ Array

Returns the list of protected methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed.

Returns:



271
272
273
274
275
276
277
# File 'mruby/mrbgems/mruby-metaprog/src/metaprog.c', line 271

static mrb_value
mrb_obj_protected_methods(mrb_state *mrb, mrb_value self)
{
  mrb_bool recur = TRUE;
  mrb_get_args(mrb, "|b", &recur);
  return mrb_obj_methods(mrb, recur, self, NOEX_PROTECTED); /* protected attribute not define */
}

#public_methods(all = true) ⇒ Array

Returns the list of public methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed.

Returns:



288
289
290
291
292
293
294
# File 'mruby/mrbgems/mruby-metaprog/src/metaprog.c', line 288

static mrb_value
mrb_obj_public_methods(mrb_state *mrb, mrb_value self)
{
  mrb_bool recur = TRUE;
  mrb_get_args(mrb, "|b", &recur);
  return mrb_obj_methods(mrb, recur, self, NOEX_PUBLIC); /* public attribute not define */
}

#puts(*args) ⇒ Object

15.3.1.2.11 15.3.1.3.39



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'mruby/mrbgems/mruby-print/mrblib/print.rb', line 35

def puts(*args)
  i = 0
  len = args.size
  while i < len
    s = args[i]
    if s.kind_of?(Array)
      puts(*s)
    else
      s = s.to_s
      __printstr__ s
      __printstr__ "\n" if (s[-1] != "\n")
    end
    i += 1
  end
  __printstr__ "\n" if len == 0
end

#raiseObject #raise(string) ⇒ Object #raise(exception[, string]) ⇒ Object

With no arguments, raises a RuntimeError With a single String argument, raises a RuntimeError with the string as a message. Otherwise, the first parameter should be the name of an Exception class (or an object that returns an Exception object when sent an exception message). The optional second parameter sets the message associated with the exception, and the third parameter is an array of callback information. Exceptions are caught by the rescue clause of begin...end blocks.

raise "Failed to create socket"
raise ArgumentError, "No parameters", caller


380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# File 'mruby/src/kernel.c', line 380

MRB_API mrb_value
mrb_f_raise(mrb_state *mrb, mrb_value self)
{
  mrb_value a[2], exc;
  mrb_int argc;

  argc = mrb_get_args(mrb, "|oo", &a[0], &a[1]);
  mrb->c->ci->mid = 0;
  switch (argc) {
  case 0:
    mrb_raise(mrb, E_RUNTIME_ERROR, "");
    break;
  case 1:
    if (mrb_string_p(a[0])) {
      a[1] = a[0];
      argc = 2;
      a[0] = mrb_obj_value(E_RUNTIME_ERROR);
    }
    /* fall through */
  default:
    exc = mrb_make_exception(mrb, argc, a);
    mrb_exc_raise(mrb, exc);
    break;
  }
  return mrb_nil_value();            /* not reached */
}

#remove_instance_variable(symbol) ⇒ Object

Removes the named instance variable from obj, returning that variable’s value.

class Dummy
  attr_reader :var
  def initialize
    @var = 99
  end
  def remove
    remove_instance_variable(:@var)
  end
end
d = Dummy.new
d.var      #=> 99
d.remove   #=> 99
d.var      #=> nil

Returns:



429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'mruby/src/kernel.c', line 429

static mrb_value
mrb_obj_remove_instance_variable(mrb_state *mrb, mrb_value self)
{
  mrb_sym sym;
  mrb_value val;

  mrb_get_args(mrb, "n", &sym);
  mrb_iv_name_sym_check(mrb, sym);
  val = mrb_iv_remove(mrb, self, sym);
  if (mrb_undef_p(val)) {
    mrb_name_error(mrb, sym, "instance variable %n not defined", sym);
  }
  return val;
}

#respond_to?(symbol, include_private = false) ⇒ Boolean

Returns true if obj responds to the given method. Private methods are included in the search only if the optional second parameter evaluates to true.

If the method is not implemented, as Process.fork on Windows, File.lchmod on GNU/Linux, etc., false is returned.

If the method is not defined, respond_to_missing? method is called and the result is returned.

Returns:

  • (Boolean)


466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# File 'mruby/src/kernel.c', line 466

static mrb_value
obj_respond_to(mrb_state *mrb, mrb_value self)
{
  mrb_sym id, rtm_id;
  mrb_bool priv = FALSE, respond_to_p;

  mrb_get_args(mrb, "n|b", &id, &priv);
  respond_to_p = basic_obj_respond_to(mrb, self, id, !priv);
  if (!respond_to_p) {
    rtm_id = MRB_SYM_Q(respond_to_missing);
    if (basic_obj_respond_to(mrb, self, rtm_id, !priv)) {
      mrb_value args[2], v;
      args[0] = mrb_symbol_value(id);
      args[1] = mrb_bool_value(priv);
      v = mrb_funcall_argv(mrb, self, rtm_id, 2, args);
      return mrb_bool_value(mrb_bool(v));
    }
  }
  return mrb_bool_value(respond_to_p);
}

#send(symbol[, args...]) ⇒ Object #__send__(symbol[, args...]) ⇒ Object

Invokes the method identified by symbol, passing it any arguments specified. You can use __send__ if the name send clashes with an existing method in obj.

class Klass
  def hello(*args)
    "Hello " + args.join(' ')
  end
end
k = Klass.new
k.send :hello, "gentle", "readers"   #=> "Hello gentle readers"

Overloads:



786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
# File 'mruby/src/vm.c', line 786

mrb_value
mrb_f_send(mrb_state *mrb, mrb_value self)
{
  mrb_sym name;
  mrb_value block, *regs;
  mrb_method_t m;
  struct RClass *c;
  mrb_callinfo *ci = mrb->c->ci;
  int n = ci->n;

  if (ci->cci > CINFO_NONE) {
  funcall:;
    const mrb_value *argv;
    mrb_int argc;
    mrb_get_args(mrb, "n*&", &name, &argv, &argc, &block);
    return mrb_funcall_with_block(mrb, self, name, argc, argv, block);
  }

  regs = mrb->c->ci->stack+1;

  if (n == 0) {
  argnum_error:
    mrb_argnum_error(mrb, 0, 1, -1);
  }
  else if (n == 15) {
    if (RARRAY_LEN(regs[0]) == 0) goto argnum_error;
    name = mrb_obj_to_sym(mrb, RARRAY_PTR(regs[0])[0]);
  }
  else {
    name = mrb_obj_to_sym(mrb, regs[0]);
  }

  c = mrb_class(mrb, self);
  m = mrb_vm_find_method(mrb, c, &c, name);
  if (MRB_METHOD_UNDEF_P(m)) {            /* call method_mising */
    goto funcall;
  }

  ci->mid = name;
  ci->u.target_class = c;
  /* remove first symbol from arguments */
  if (n == 15) {     /* variable length arguments */
    regs[0] = mrb_ary_subseq(mrb, regs[0], 1, RARRAY_LEN(regs[0]) - 1);
  }
  else { /* n > 0 */
    for (int i=0; i<n; i++) {
      regs[i] = regs[i+1];
    }
    regs[n] = regs[n+1];        /* copy kdict or block */
    if (ci->nk > 0) {
      regs[n+1] = regs[n+2];    /* copy block */
    }
    ci->n--;
  }

  if (MRB_METHOD_CFUNC_P(m)) {
    if (MRB_METHOD_NOARG_P(m)) {
      check_method_noarg(mrb, ci);
    }

    if (MRB_METHOD_PROC_P(m)) {
      const struct RProc *p = MRB_METHOD_PROC(m);
      CI_PROC_SET(ci, p);
    }
    return MRB_METHOD_CFUNC(m)(mrb, self);
  }
  return exec_irep(mrb, self, MRB_METHOD_PROC(m));
}

#singleton_classObject

15.3.1.3.28 (15.3.1.2.7)



1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
# File 'mruby/src/class.c', line 1689

MRB_API mrb_value
mrb_singleton_class(mrb_state *mrb, mrb_value v)
{
  struct RClass *c = mrb_singleton_class_ptr(mrb, v);

  if (c == NULL) {
    mrb_raise(mrb, E_TYPE_ERROR, "can't define singleton");
  }
  return mrb_obj_value(c);
}

#singleton_method(name) ⇒ Object



2
3
4
5
6
7
8
9
# File 'mruby/mrbgems/mruby-method/mrblib/kernel.rb', line 2

def singleton_method(name)
  m = method(name)
  sc = (class <<self; self; end)
  if m.owner != sc
    raise NameError, "undefined method '#{name}' for class '#{sc}'"
  end
  m
end

#singleton_methods(all = true) ⇒ Array

Returns an array of the names of singleton methods for obj. If the optional all parameter is true, the list will include methods in modules included in obj. Only public and protected singleton methods are returned.

module Other
  def three() end
end

class Single
  def Single.four() end
end

a = Single.new

def a.one()
end

class << a
  include Other
  def two()
  end
end

Single.singleton_methods    #=> [:four]
a.singleton_methods(false)  #=> [:two, :one]
a.singleton_methods         #=> [:two, :one, :three]

Returns:



363
364
365
366
367
368
369
# File 'mruby/mrbgems/mruby-metaprog/src/metaprog.c', line 363

static mrb_value
mrb_obj_singleton_methods_m(mrb_state *mrb, mrb_value self)
{
  mrb_bool recur = TRUE;
  mrb_get_args(mrb, "|b", &recur);
  return mrb_obj_singleton_methods(mrb, recur, self);
}

#tap {|_self| ... } ⇒ Object

call-seq:

   obj.tap{|x|...}    -> obj

Yields <code>x</code> to the block, and then returns <code>x</code>.
The primary purpose of this method is to "tap into" a method chain,
in order to perform operations on intermediate results within the chain.

(1..10)                .tap {|x| puts "original: #{x.inspect}"}
  .to_a                .tap {|x| puts "array: #{x.inspect}"}
  .select {|x| x%2==0} .tap {|x| puts "evens: #{x.inspect}"}
  .map { |x| x*x }     .tap {|x| puts "squares: #{x.inspect}"}

Yields:

  • (_self)

Yield Parameters:

  • _self (Kernel)

    the object that the method was called on



29
30
31
32
# File 'mruby/mrbgems/mruby-object-ext/mrblib/object.rb', line 29

def tap
  yield self
  self
end

#to_enum(meth = :each, *args) ⇒ Object Also known as: enum_for

call-seq:

obj.to_enum(method = :each, *args)                 -> enum
obj.enum_for(method = :each, *args)                -> enum

Creates a new Enumerator which will enumerate by calling method on obj, passing args if any.

Examples

str = "xyz"

enum = str.enum_for(:each_byte)
enum.each { |b| puts b }
# => 120
# => 121
# => 122

# protect an array from being modified by some_method
a = [1, 2, 3]
some_method(a.to_enum)

It is typical to call to_enum when defining methods for a generic Enumerable, in case no block is passed.

Here is such an example with parameter passing:

module Enumerable
  # a generic method to repeat the values of any enumerable
  def repeat(n)
    raise ArgumentError, "#{n} is negative!" if n < 0
    unless block_given?
      return to_enum(__callee__, n) do # __callee__ is :repeat here
    end
    each do |*val|
      n.times { yield *val }
    end
  end
end

%i[hello world].repeat(2) { |w| puts w }
  # => Prints 'hello', 'hello', 'world', 'world'
enum = (1..14).repeat(3)
  # => returns an Enumerator when called without a block
enum.first(4) # => [1, 1, 1, 2]


650
651
652
# File 'mruby/mrbgems/mruby-enumerator/mrblib/enumerator.rb', line 650

def to_enum(*a)
  raise NotImplementedError.new("fiber required for enumerator")
end

#to_sObject

15.3.1.3.46

#yield_self(&block) ⇒ Object Also known as: then

call-seq:

obj.yield_self {|_obj|...} -> an_object
obj.then {|_obj|...}       -> an_object

Yields obj and returns the result.

'my string'.yield_self {|s|s.upcase} #=> "MY STRING"


10
11
12
13
# File 'mruby/mrbgems/mruby-object-ext/mrblib/object.rb', line 10

def yield_self(&block)
  return to_enum :yield_self unless block
  block.call(self)
end