[ruby-core:103086] [Ruby master Bug#17739] Array#sort! changes the order even if the receiver raises FrozenError in given block
From:
merch-redmine@...
Date:
2021-03-29 23:10:18 UTC
List:
ruby-core #103086
Issue #17739 has been updated by jeremyevans0 (Jeremy Evans).
I think this is a bug, but it's not that `Array#sort!` should keep the initial order of the receiver, it's that it should keep the order at the point `freeze` is called, and it does not:
```ruby
array = [1, 2, 3, 4, 5]
begin
array.sort! do |a, b|
array.freeze if a == 3
p [array.frozen?, array]
1
end
rescue => err
p err #=> #<FrozenError: can't modify frozen Array: [5, 4, 3, 2, 1]>
end
```
Output
```
[false, [1, 2, 3, 4, 5]]
[true, [1, 2, 3, 4, 5]]
[true, [5, 2, 3, 4, 1]]
[true, [5, 2, 3, 4, 1]]
[true, [5, 3, 2, 4, 1]]
[true, [5, 3, 2, 4, 1]]
#<FrozenError: can't modify frozen Array: [5, 3, 1, 4, 2]>
```
Notice that the array's order is changed after it has been frozen.
I've added a pull request to fix this: https://github.com/ruby/ruby/pull/4335
----------------------------------------
Bug #17739: Array#sort! changes the order even if the receiver raises FrozenError in given block
https://bugs.ruby-lang.org/issues/17739#change-91150
* Author: kachick (Kenichi Kamiya)
* Status: Open
* Priority: Normal
* ruby -v: ruby 3.0.0p0 (2020-12-25 revision 95aff21468) [x86_64-darwin20]
* Backport: 2.5: UNKNOWN, 2.6: UNKNOWN, 2.7: UNKNOWN, 3.0: UNKNOWN
----------------------------------------
I think this is a similar issue of https://bugs.ruby-lang.org/issues/17736
```ruby
array = [1, 2, 3, 4, 5]
begin
array.sort! do |a, b|
array.freeze if a == 3
1
end
rescue => err
p err #=> #<FrozenError: can't modify frozen Array: [5, 4, 3, 2, 1]>
end
p array #=> [5, 4, 3, 2, 1]
array = [1, 2, 3, 4, 5]
array.sort! do |a, b|
break if a == 3
1
end
p array #=> [3, 4, 2, 1, 5]
```
Array#sort! raises a FrozenError as expected, but the order is changed. I would expect the order is kept after frozen.
--
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>