[ruby-core:75821] [Ruby trunk Bug#12437] Is it "legal" to call collect! in class initializer?

From: prijutme4ty@...
Date: 2016-06-01 12:05:26 UTC
List: ruby-core #75821
Issue #12437 has been updated by Ilya Vorontsov.


Second call to `categories.collect!` works over Categories object. `Set#collect!` tries to create a new set. `Categories.collect!` in turn tries to create new `Categories`.

```ruby
s=Set.new([1,2,3])
s.object_id # => 7618880
s.collect!{|x| x**2 }
s.object_id # => 7618880 (the same)
s # => #<Set: {1, 4, 9}>

class Categories < Set; end
c = Categories.new([1,2,3])
c.object_id # => 7508680
c.collect!{|x| x**2 }
c.object_id # => 7508680 (the same)
c # => #<Categories: {1, 4, 9}>
```

Problem is that `Set#collect!` calls #initialize (probably to maintain some Set properties):

```ruby
class Categories < Set
  def initialize(*args, &block)
    puts "call to #initialize"
    super
  end
end

c = Categories.new([1,2,3])
# => call to #initalize
c.collect!{|x| x ** 2 }
# => call to #initalize
```

----------------------------------------
Bug #12437: Is it "legal" to call collect! in class initializer?
https://bugs.ruby-lang.org/issues/12437#change-59002

* Author: Vit Ondruch
* Status: Assigned
* Priority: Normal
* Assignee: Akinori MUSHA
* ruby -v: ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]
* Backport: 2.1: DONTNEED, 2.2: DONTNEED, 2.3: REQUIRED
----------------------------------------
Is there any reason the following script should not work?

```ruby
#! /usr/bin/ruby

require 'set'

class Categories < Set

  def initialize(categories=[])
    categories.collect! { |category| category } if categories
    super categories
  end

end

categories = Categories.new()
categories += [1, 2, 3]
p categories

categories2 = Categories.new(categories)
p categories2
```

It fails with ```stack level too deep (SystemStackError)``` error and this regression seems to be introduced by r52591.

For details, please take a look at original issue reported here: https://bugzilla.redhat.com/show_bug.cgi?id=1308057




-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>

In This Thread

Prev Next