Commit b6edf24a authored by Jun Hiroe's avatar Jun Hiroe

Add Kernel.Array

parent 3f063073
#include "mruby.h" #include "mruby.h"
#include "mruby/error.h" #include "mruby/error.h"
#include "mruby/object.h"
#include "mruby/array.h"
/* /*
* call-seq: * call-seq:
...@@ -21,6 +23,40 @@ mrb_f_method(mrb_state *mrb, mrb_value self) ...@@ -21,6 +23,40 @@ mrb_f_method(mrb_state *mrb, mrb_value self)
return mrb_nil_value(); return mrb_nil_value();
} }
/*
* call-seq:
* Array(arg) -> array
*
* Returns +arg+ as an Array.
*
* First tries to call Array#to_ary on +arg+, then Array#to_a.
*
* Array(1..5) #=> [1, 2, 3, 4, 5]
*
*/
static mrb_value
mrb_f_array(mrb_state *mrb, mrb_value self)
{
mrb_value argv, tmp;
mrb_get_args(mrb, "o", &argv);
tmp = mrb_check_array_type(mrb, argv);
if (mrb_nil_p(tmp)) {
tmp = mrb_check_convert_type(mrb, argv, MRB_TT_ARRAY, "Array", "to_a");
}
if (mrb_nil_p(tmp)) {
struct RArray *a;
tmp = mrb_ary_new_capa(mrb, 1);
a = mrb_ary_ptr(tmp);
a->ptr[0] = argv;
a->len = 1;
}
return tmp;
}
void void
mrb_mruby_kernel_ext_gem_init(mrb_state *mrb) mrb_mruby_kernel_ext_gem_init(mrb_state *mrb)
{ {
...@@ -28,6 +64,7 @@ mrb_mruby_kernel_ext_gem_init(mrb_state *mrb) ...@@ -28,6 +64,7 @@ mrb_mruby_kernel_ext_gem_init(mrb_state *mrb)
mrb_define_module_function(mrb, krn, "fail", mrb_f_raise, MRB_ARGS_OPT(2)); mrb_define_module_function(mrb, krn, "fail", mrb_f_raise, MRB_ARGS_OPT(2));
mrb_define_method(mrb, krn, "__method__", mrb_f_method, MRB_ARGS_NONE()); mrb_define_method(mrb, krn, "__method__", mrb_f_method, MRB_ARGS_NONE());
mrb_define_module_function(mrb, krn, "Array", mrb_f_array, MRB_ARGS_REQ(1));
} }
void void
......
...@@ -16,3 +16,10 @@ assert('Kernel#__method__') do ...@@ -16,3 +16,10 @@ assert('Kernel#__method__') do
assert_equal(:m1, c.new.m1) assert_equal(:m1, c.new.m1)
assert_equal(:m2, c.new.m2) assert_equal(:m2, c.new.m2)
end end
assert('Kernel#Array') do
assert_equal([1], Kernel.Array(1))
assert_equal([1, 2, 3, 4, 5], Kernel.Array([1, 2, 3, 4, 5]))
assert_equal([1, 2, 3, 4, 5], Kernel.Array(1..5))
assert_equal([[:a, 1], [:b, 2], [:c, 3]], Kernel.Array({a:1, b:2, c:3}))
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment