Merge pull request #2091 from take-cheeze/struct_len

Implement Struct#size and Struct#length .
This commit is contained in:
Yukihiro "Matz" Matsumoto
2014-04-21 00:43:17 +09:00
2 changed files with 22 additions and 0 deletions
+16
View File
@@ -779,6 +779,19 @@ mrb_struct_eql(mrb_state *mrb, mrb_value s)
return mrb_bool_value(eql_p);
}
/*
* call-seq:
* struct.length -> Fixnum
* struct.size -> Fixnum
*
* Returns number of struct members.
*/
static mrb_value
mrb_struct_len(mrb_state *mrb, mrb_value self)
{
return mrb_fixnum_value(RSTRUCT_LEN(self));
}
/*
* A <code>Struct</code> is a convenient way to bundle a number of
* attributes together, using accessor methods, without having to write
@@ -811,6 +824,9 @@ mrb_mruby_struct_gem_init(mrb_state* mrb)
mrb_define_method(mrb, st, "inspect", mrb_struct_inspect, MRB_ARGS_NONE()); /* 15.2.18.4.10(x) */
mrb_define_alias(mrb, st, "to_s", "inspect"); /* 15.2.18.4.11(x) */
mrb_define_method(mrb, st, "eql?", mrb_struct_eql, MRB_ARGS_REQ(1)); /* 15.2.18.4.12(x) */
mrb_define_method(mrb, st, "size", mrb_struct_len, MRB_ARGS_NONE());
mrb_define_method(mrb, st, "length", mrb_struct_len, MRB_ARGS_NONE());
}
void
+6
View File
@@ -107,4 +107,10 @@ if Object.const_defined?(:Struct)
cc = c.new(1,2,3,4,5)
assert_equal "#<struct #{c.inspect} m1=1, m2=2, m3=3, m4=4, m5=5>", cc.inspect
end
assert('Struct#length, Struct#size') do
s = Struct.new(:f1, :f2).new(0, 1)
assert_equal 2, s.size
assert_equal 2, s.length
end
end