Skip to content

Commit 34cc80d

Browse files
olivier-thatchbyroot
authored andcommitted
Fix Enumerable#sole when element is a tuple
Fix rails#55807
1 parent 5b8d385 commit 34cc80d

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

activesupport/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
* Fix `Enumerable#sole` to return the full tuple instead of just the first element of the tuple.
2+
3+
*Olivier Bellone*
4+
15
* Fix parallel tests hanging when worker processes die abruptly.
26

37
Previously, if a worker process was killed (e.g., OOM killed, `kill -9`) during parallel

activesupport/lib/active_support/core_ext/enumerable.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -212,12 +212,12 @@ def sole
212212
result = nil
213213
found = false
214214

215-
each do |element|
215+
each do |*element|
216216
if found
217217
raise SoleItemExpectedError, "multiple items found"
218218
end
219219

220-
result = element
220+
result = element.size == 1 ? element[0] : element
221221
found = true
222222
end
223223

activesupport/test/core_ext/enumerable_test.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -401,6 +401,26 @@ def test_sole
401401
assert_raise(expected_raise) { GenericEnumerable.new(1..).sole }
402402
end
403403

404+
def test_sole_returns_same_value_as_first_for_tuples
405+
enum = Enumerator.new(1) { |yielder| yielder.yield(1, "one") }
406+
assert_equal [1, "one"], enum.sole
407+
assert_equal enum.first, enum.sole
408+
end
409+
410+
class KeywordYielder
411+
include Enumerable
412+
413+
def each
414+
yield 1, two: 3
415+
end
416+
end
417+
418+
def test_sole_keyword_arguments
419+
yielder = KeywordYielder.new
420+
assert_equal [1, { two: 3 }], yielder.sole
421+
assert_equal yielder.first, yielder.sole
422+
end
423+
404424
def test_doesnt_bust_constant_cache
405425
skip "Only applies to MRI" unless defined?(RubyVM.stat)
406426

0 commit comments

Comments
 (0)