Commit d3c7e117 authored by Yukihiro "Matz" Matsumoto's avatar Yukihiro "Matz" Matsumoto

Merge pull request #2617 from suzukaze/add-kernel.Hash

Add Kernel#Hash
parents 5616208e 9e053664
#include "mruby.h"
#include "mruby/error.h"
#include "mruby/array.h"
#include "mruby/hash.h"
/*
* call-seq:
......@@ -75,6 +76,39 @@ mrb_f_array(mrb_state *mrb, mrb_value self)
return tmp;
}
/*
* call-seq:
* Hash(arg) -> hash
*
* Converts <i>arg</i> to a <code>Hash</code> by calling
* <i>arg</i><code>.to_hash</code>. Returns an empty <code>Hash</code> when
* <i>arg</i> is <tt>nil</tt> or <tt>[]</tt>.
*
* Hash([]) #=> {}
* Hash(nil) #=> {}
* Hash(key: :value) #=> {:key => :value}
* Hash([1, 2, 3]) #=> TypeError
*/
static mrb_value
mrb_f_hash(mrb_state *mrb, mrb_value self)
{
mrb_value arg, tmp;
mrb_get_args(mrb, "o", &arg);
if (mrb_nil_p(arg)) {
return mrb_hash_new(mrb);
}
tmp = mrb_check_convert_type(mrb, arg, MRB_TT_HASH, "Hash", "to_hash");
if (mrb_nil_p(tmp)) {
if (mrb_array_p(arg) && RARRAY_LEN(arg) == 0) {
return mrb_hash_new(mrb);
}
mrb_raisef(mrb, E_TYPE_ERROR, "can't convert %S into Hash",
mrb_str_new_cstr(mrb, mrb_obj_classname(mrb, arg)));
}
return tmp;
}
void
mrb_mruby_kernel_ext_gem_init(mrb_state *mrb)
{
......@@ -84,6 +118,7 @@ mrb_mruby_kernel_ext_gem_init(mrb_state *mrb)
mrb_define_method(mrb, krn, "__method__", mrb_f_method, MRB_ARGS_NONE());
mrb_define_module_function(mrb, krn, "String", mrb_f_string, MRB_ARGS_REQ(1));
mrb_define_module_function(mrb, krn, "Array", mrb_f_array, MRB_ARGS_REQ(1));
mrb_define_module_function(mrb, krn, "Hash", mrb_f_hash, MRB_ARGS_REQ(1));
}
void
......
......@@ -29,3 +29,10 @@ assert('Kernel#Array') do
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
assert('Kernel#Hash') do
assert_equal({}, Hash([]))
assert_equal({}, Hash(nil))
assert_equal({:key => :value}, Hash(key: :value))
assert_raise(TypeError) { Hash([1, 2, 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