From: nobu@... Date: 2018-08-29T14:12:45+00:00 Subject: [ruby-core:88733] [Ruby trunk Bug#15027] When Struct#each method is overriden Struct#select and Struct#to_a use wrong collections Issue #15027 has been updated by nobu (Nobuyoshi Nakada). ```diff diff --git a/struct.c b/struct.c index 7de46980aa..e4c875b5be 100644 --- a/struct.c +++ b/struct.c @@ -860,6 +860,9 @@ rb_struct_inspect(VALUE s) static VALUE rb_struct_to_a(VALUE s) { + if (!rb_method_basic_definition_p(CLASS_OF(s), idEach)) { + return rb_call_super(0, 0); + } return rb_ary_new4(RSTRUCT_LEN(s), RSTRUCT_CONST_PTR(s)); } @@ -1077,6 +1080,9 @@ rb_struct_select(int argc, VALUE *argv, VALUE s) rb_check_arity(argc, 0, 0); RETURN_SIZED_ENUMERATOR(s, 0, 0, struct_enum_size); + if (!rb_method_basic_definition_p(CLASS_OF(s), idEach)) { + return rb_call_super(argc, argv); + } result = rb_ary_new(); for (i = 0; i < RSTRUCT_LEN(s); i++) { if (RTEST(rb_yield(RSTRUCT_GET(s, i)))) { ``` ---------------------------------------- Bug #15027: When Struct#each method is overriden Struct#select and Struct#to_a use wrong collections https://bugs.ruby-lang.org/issues/15027#change-73788 * Author: bruno (Bruno Sutic) * Status: Feedback * Priority: Normal * Assignee: * Target version: * ruby -v: 2.6.0dev * Backport: 2.3: UNKNOWN, 2.4: UNKNOWN, 2.5: UNKNOWN ---------------------------------------- ### Bug Here's the code snippet that should reproduce the problem: ~~~ ruby class Foo < Struct.new(:bar) def each(&block) [:baz, :qux].each(&block) end end foo = Foo.new(:foo) foo.map(&:itself) # => [:baz, :qux] # OK foo.to_a # => [:foo] # NOT OK, expected [:baz, :qux] foo.select(&:itself) # => [:foo] # NOT OK, expected [:baz, :qux] ~~~ As you can see, even tho we defined another collection for use by overriding `#each`, the `to_a` and `select` still use `Struct`'s original collection. The problem seem to be with `Struct#to_a` and `Struct#select` methods from `struct.c` file that are defined unnecessarily. ### Proposed solution The attached solution simply deletes `Struct#select` and `Struct#to_a`. A couple tests are added to show everything still works as before. Please let me know if I can provide any more info and I'll be ready to do so. ---Files-------------------------------- struct_enumerable_fix.patch (2.8 KB) -- https://bugs.ruby-lang.org/ Unsubscribe: