[](p1)
public
Attribute Reference—Returns the
value of the given struct member or the member at the given
index. Raises NameError if the
member does not exist and IndexError if the index is out of
range.
Customer = Struct.new(:name, :address, :zip)
joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
joe["name"]
joe[:name]
joe[0]
Show source
VALUE
rb_struct_aref(VALUE s, VALUE idx)
{
long i;
if (RB_TYPE_P(idx, T_SYMBOL)) {
return rb_struct_aref_id(s, SYM2ID(idx));
}
else if (RB_TYPE_P(idx, T_STRING)) {
ID id = rb_check_id(&idx);
if (!id) {
rb_name_error_str(idx, "no member '%"PRIsVALUE"' in struct",
QUOTE(idx));
}
return rb_struct_aref_id(s, id);
}
i = NUM2LONG(idx);
if (i < 0) i = RSTRUCT_LEN(s) + i;
if (i < 0)
rb_raise(rb_eIndexError, "offset %ld too small for struct(size:%ld)",
i, RSTRUCT_LEN(s));
if (RSTRUCT_LEN(s) <= i)
rb_raise(rb_eIndexError, "offset %ld too large for struct(size:%ld)",
i, RSTRUCT_LEN(s));
return RSTRUCT_GET(s, i);
}