Actions
Bug #16270
closedStrange behavior on Hash's #each and #select method.
Description
The following is some example code:
sample_hash = {
"246" => {
"price" => "8000",
"note" => ""
},
"247" => {
"price" => "8000",
"note" => ""
},
"248" => {
"price" => "8000",
"note" => ""
}
}
sample_hash.each {|e| p e}
# The following is p's output content. We can see that e is a hash element, and is converted into an array object.
# This is expected behavior maybe. Anyway, a hash is the same as a nested array.
["246", {"price"=>"8000", "note"=>""}]
["247", {"price"=>"8000", "note"=>""}]
["248", {"price"=>"8000", "note"=>""}]
sample_hash.select {|e| p e }
# Wired(?). Why is e's output this time different from each?
"246"
"247"
"248"
The following is source code for each
static VALUE
rb_hash_each_pair(VALUE hash)
{
RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
if (rb_block_arity() > 1)
rb_hash_foreach(hash, each_pair_i_fast, 0);
else
rb_hash_foreach(hash, each_pair_i, 0);
return hash;
}
The following is source code for select
VALUE
rb_hash_select(VALUE hash)
{
VALUE result;
RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
result = rb_hash_new();
if (!RHASH_EMPTY_P(hash)) {
rb_hash_foreach(hash, select_i, result);
}
return result;
}
I don't understand C well, and don't know why the above two Hash methods lack consistency. But I think it confuses me a little.
Actions
Like0
Like0Like0Like0Like0