PageRenderTime 54ms CodeModel.GetById 1ms RepoModel.GetById 1ms app.codeStats 0ms

/test/ruby/test_enum.rb

http://github.com/ruby/ruby
Ruby | 1161 lines | 995 code | 165 blank | 1 comment | 59 complexity | e5f15c86f8aba4491d4928b79b926055 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, AGPL-3.0
  1. # frozen_string_literal: false
  2. require 'test/unit'
  3. EnvUtil.suppress_warning {require 'continuation'}
  4. require 'stringio'
  5. class TestEnumerable < Test::Unit::TestCase
  6. def setup
  7. @obj = Object.new
  8. class << @obj
  9. include Enumerable
  10. def each
  11. yield 1
  12. yield 2
  13. yield 3
  14. yield 1
  15. yield 2
  16. self
  17. end
  18. end
  19. @empty = Object.new
  20. class << @empty
  21. attr_reader :block
  22. include Enumerable
  23. def each(&block)
  24. @block = block
  25. self
  26. end
  27. end
  28. @verbose = $VERBOSE
  29. $VERBOSE = nil
  30. end
  31. def teardown
  32. $VERBOSE = @verbose
  33. end
  34. def test_grep_v
  35. assert_equal([3], @obj.grep_v(1..2))
  36. a = []
  37. @obj.grep_v(2) {|x| a << x }
  38. assert_equal([1, 3, 1], a)
  39. a = []
  40. lambda = ->(x, i) {a << [x, i]}
  41. @obj.each_with_index.grep_v(proc{|x,i|x!=2}, &lambda)
  42. assert_equal([[2, 1], [2, 4]], a)
  43. end
  44. def test_grep
  45. assert_equal([1, 2, 1, 2], @obj.grep(1..2))
  46. a = []
  47. @obj.grep(2) {|x| a << x }
  48. assert_equal([2, 2], a)
  49. bug5801 = '[ruby-dev:45041]'
  50. @empty.grep(//)
  51. block = @empty.block
  52. assert_nothing_raised(bug5801) {100.times {block.call}}
  53. a = []
  54. lambda = ->(x, i) {a << [x, i]}
  55. @obj.each_with_index.grep(proc{|x,i|x==2}, &lambda)
  56. assert_equal([[2, 1], [2, 4]], a)
  57. end
  58. def test_count
  59. assert_equal(5, @obj.count)
  60. assert_equal(2, @obj.count(1))
  61. assert_equal(3, @obj.count {|x| x % 2 == 1 })
  62. assert_equal(2, @obj.count(1) {|x| x % 2 == 1 })
  63. assert_raise(ArgumentError) { @obj.count(0, 1) }
  64. if RUBY_ENGINE == "ruby"
  65. en = Class.new {
  66. include Enumerable
  67. alias :size :count
  68. def each
  69. yield 1
  70. end
  71. }
  72. assert_equal(1, en.new.count, '[ruby-core:24794]')
  73. end
  74. end
  75. def test_find
  76. assert_equal(2, @obj.find {|x| x % 2 == 0 })
  77. assert_equal(nil, @obj.find {|x| false })
  78. assert_equal(:foo, @obj.find(proc { :foo }) {|x| false })
  79. cond = ->(x, i) { x % 2 == 0 }
  80. assert_equal([2, 1], @obj.each_with_index.find(&cond))
  81. end
  82. def test_find_index
  83. assert_equal(1, @obj.find_index(2))
  84. assert_equal(1, @obj.find_index {|x| x % 2 == 0 })
  85. assert_equal(nil, @obj.find_index {|x| false })
  86. assert_raise(ArgumentError) { @obj.find_index(0, 1) }
  87. assert_equal(1, @obj.find_index(2) {|x| x == 1 })
  88. end
  89. def test_find_all
  90. assert_equal([1, 3, 1], @obj.find_all {|x| x % 2 == 1 })
  91. cond = ->(x, i) { x % 2 == 1 }
  92. assert_equal([[1, 0], [3, 2], [1, 3]], @obj.each_with_index.find_all(&cond))
  93. end
  94. def test_reject
  95. assert_equal([2, 3, 2], @obj.reject {|x| x < 2 })
  96. cond = ->(x, i) {x < 2}
  97. assert_equal([[2, 1], [3, 2], [2, 4]], @obj.each_with_index.reject(&cond))
  98. end
  99. def test_to_a
  100. assert_equal([1, 2, 3, 1, 2], @obj.to_a)
  101. end
  102. def test_to_a_size_symbol
  103. sym = Object.new
  104. class << sym
  105. include Enumerable
  106. def each
  107. self
  108. end
  109. def size
  110. :size
  111. end
  112. end
  113. assert_equal([], sym.to_a)
  114. end
  115. def test_to_a_size_infinity
  116. inf = Object.new
  117. class << inf
  118. include Enumerable
  119. def each
  120. self
  121. end
  122. def size
  123. Float::INFINITY
  124. end
  125. end
  126. assert_equal([], inf.to_a)
  127. end
  128. StubToH = Object.new.tap do |obj|
  129. def obj.each(*args)
  130. yield(*args)
  131. yield [:key, :value]
  132. yield :other_key, :other_value
  133. kvp = Object.new
  134. def kvp.to_ary
  135. [:obtained, :via_to_ary]
  136. end
  137. yield kvp
  138. end
  139. obj.extend Enumerable
  140. obj.freeze
  141. end
  142. def test_to_h
  143. obj = StubToH
  144. assert_equal({
  145. :hello => :world,
  146. :key => :value,
  147. :other_key => :other_value,
  148. :obtained => :via_to_ary,
  149. }, obj.to_h(:hello, :world))
  150. e = assert_raise(TypeError) {
  151. obj.to_h(:not_an_array)
  152. }
  153. assert_equal "wrong element type Symbol (expected array)", e.message
  154. e = assert_raise(ArgumentError) {
  155. obj.to_h([1])
  156. }
  157. assert_equal "element has wrong array length (expected 2, was 1)", e.message
  158. end
  159. def test_to_h_block
  160. obj = StubToH
  161. assert_equal({
  162. "hello" => "world",
  163. "key" => "value",
  164. "other_key" => "other_value",
  165. "obtained" => "via_to_ary",
  166. }, obj.to_h(:hello, :world) {|k, v| [k.to_s, v.to_s]})
  167. e = assert_raise(TypeError) {
  168. obj.to_h {:not_an_array}
  169. }
  170. assert_equal "wrong element type Symbol (expected array)", e.message
  171. e = assert_raise(ArgumentError) {
  172. obj.to_h {[1]}
  173. }
  174. assert_equal "element has wrong array length (expected 2, was 1)", e.message
  175. end
  176. def test_inject
  177. assert_equal(12, @obj.inject {|z, x| z * x })
  178. assert_equal(48, @obj.inject {|z, x| z * 2 + x })
  179. assert_equal(12, @obj.inject(:*))
  180. assert_equal(24, @obj.inject(2) {|z, x| z * x })
  181. assert_equal(24, @obj.inject(2, :*) {|z, x| z * x })
  182. assert_equal(nil, @empty.inject() {9})
  183. end
  184. FIXNUM_MIN = RbConfig::LIMITS['FIXNUM_MIN']
  185. FIXNUM_MAX = RbConfig::LIMITS['FIXNUM_MAX']
  186. def test_inject_array_mul
  187. assert_equal(nil, [].inject(:*))
  188. assert_equal(5, [5].inject(:*))
  189. assert_equal(35, [5, 7].inject(:*))
  190. assert_equal(3, [].inject(3, :*))
  191. assert_equal(15, [5].inject(3, :*))
  192. assert_equal(105, [5, 7].inject(3, :*))
  193. end
  194. def test_inject_array_plus
  195. assert_equal(3, [3].inject(:+))
  196. assert_equal(8, [3, 5].inject(:+))
  197. assert_equal(15, [3, 5, 7].inject(:+))
  198. assert_float_equal(15.0, [3, 5, 7.0].inject(:+))
  199. assert_equal(2*FIXNUM_MAX, Array.new(2, FIXNUM_MAX).inject(:+))
  200. assert_equal(2*(FIXNUM_MAX+1), Array.new(2, FIXNUM_MAX+1).inject(:+))
  201. assert_equal(10*FIXNUM_MAX, Array.new(10, FIXNUM_MAX).inject(:+))
  202. assert_equal(0, ([FIXNUM_MAX, 1, -FIXNUM_MAX, -1]*10).inject(:+))
  203. assert_equal(FIXNUM_MAX*10, ([FIXNUM_MAX+1, -1]*10).inject(:+))
  204. assert_equal(2*FIXNUM_MIN, Array.new(2, FIXNUM_MIN).inject(:+))
  205. assert_equal((FIXNUM_MAX+1).to_f, [FIXNUM_MAX, 1, 0.0].inject(:+))
  206. assert_float_equal(10.0, [3.0, 5].inject(2.0, :+))
  207. assert_float_equal((FIXNUM_MAX+1).to_f, [0.0, FIXNUM_MAX+1].inject(:+))
  208. assert_equal(2.0+3.0i, [2.0, 3.0i].inject(:+))
  209. end
  210. def test_inject_array_op_redefined
  211. assert_separately([], "#{<<~"end;"}\n""end")
  212. all_assertions_foreach("", *%i[+ * / - %]) do |op|
  213. bug = '[ruby-dev:49510] [Bug#12178] should respect redefinition'
  214. begin
  215. Integer.class_eval do
  216. alias_method :orig, op
  217. define_method(op) do |x|
  218. 0
  219. end
  220. end
  221. assert_equal(0, [1,2,3].inject(op), bug)
  222. ensure
  223. Integer.class_eval do
  224. undef_method op
  225. alias_method op, :orig
  226. end
  227. end
  228. end;
  229. end
  230. def test_inject_array_op_private
  231. assert_separately([], "#{<<~"end;"}\n""end")
  232. all_assertions_foreach("", *%i[+ * / - %]) do |op|
  233. bug = '[ruby-core:81349] [Bug #13592] should respect visibility'
  234. assert_raise_with_message(NoMethodError, /private method/, bug) do
  235. begin
  236. Integer.class_eval do
  237. private op
  238. end
  239. [1,2,3].inject(op)
  240. ensure
  241. Integer.class_eval do
  242. public op
  243. end
  244. end
  245. end
  246. end;
  247. end
  248. def test_partition
  249. assert_equal([[1, 3, 1], [2, 2]], @obj.partition {|x| x % 2 == 1 })
  250. cond = ->(x, i) { x % 2 == 1 }
  251. assert_equal([[[1, 0], [3, 2], [1, 3]], [[2, 1], [2, 4]]], @obj.each_with_index.partition(&cond))
  252. end
  253. def test_group_by
  254. h = { 1 => [1, 1], 2 => [2, 2], 3 => [3] }
  255. assert_equal(h, @obj.group_by {|x| x })
  256. h = {1=>[[1, 0], [1, 3]], 2=>[[2, 1], [2, 4]], 3=>[[3, 2]]}
  257. cond = ->(x, i) { x }
  258. assert_equal(h, @obj.each_with_index.group_by(&cond))
  259. end
  260. def test_tally
  261. h = {1 => 2, 2 => 2, 3 => 1}
  262. assert_equal(h, @obj.tally)
  263. end
  264. def test_first
  265. assert_equal(1, @obj.first)
  266. assert_equal([1, 2, 3], @obj.first(3))
  267. assert_nil(@empty.first)
  268. assert_equal([], @empty.first(10))
  269. bug5801 = '[ruby-dev:45041]'
  270. assert_in_out_err([], <<-'end;', [], /unexpected break/, bug5801)
  271. empty = Object.new
  272. class << empty
  273. attr_reader :block
  274. include Enumerable
  275. def each(&block)
  276. @block = block
  277. self
  278. end
  279. end
  280. empty.first
  281. empty.block.call
  282. end;
  283. end
  284. def test_sort
  285. assert_equal([1, 1, 2, 2, 3], @obj.sort)
  286. assert_equal([3, 2, 2, 1, 1], @obj.sort {|x, y| y <=> x })
  287. end
  288. def test_sort_by
  289. assert_equal([3, 2, 2, 1, 1], @obj.sort_by {|x| -x })
  290. assert_equal((1..300).to_a.reverse, (1..300).sort_by {|x| -x })
  291. cond = ->(x, i) { [-x, i] }
  292. assert_equal([[3, 2], [2, 1], [2, 4], [1, 0], [1, 3]], @obj.each_with_index.sort_by(&cond))
  293. end
  294. def test_all
  295. assert_equal(true, @obj.all? {|x| x <= 3 })
  296. assert_equal(false, @obj.all? {|x| x < 3 })
  297. assert_equal(true, @obj.all?)
  298. assert_equal(false, [true, true, false].all?)
  299. assert_equal(true, [].all?)
  300. assert_equal(true, @empty.all?)
  301. assert_equal(true, @obj.all?(Fixnum))
  302. assert_equal(false, @obj.all?(1..2))
  303. end
  304. def test_all_with_unused_block
  305. assert_in_out_err [], <<-EOS, [], ["-:1: warning: given block not used"]
  306. [1, 2].all?(1) {|x| x == 3 }
  307. EOS
  308. assert_in_out_err [], <<-EOS, [], ["-:1: warning: given block not used"]
  309. (1..2).all?(1) {|x| x == 3 }
  310. EOS
  311. assert_in_out_err [], <<-EOS, [], ["-:1: warning: given block not used"]
  312. 3.times.all?(1) {|x| x == 3 }
  313. EOS
  314. assert_in_out_err [], <<-EOS, [], ["-:1: warning: given block not used"]
  315. {a: 1, b: 2}.all?([:b, 2]) {|x| x == 4 }
  316. EOS
  317. end
  318. def test_any
  319. assert_equal(true, @obj.any? {|x| x >= 3 })
  320. assert_equal(false, @obj.any? {|x| x > 3 })
  321. assert_equal(true, @obj.any?)
  322. assert_equal(false, [false, false, false].any?)
  323. assert_equal(false, [].any?)
  324. assert_equal(false, @empty.any?)
  325. assert_equal(true, @obj.any?(1..2))
  326. assert_equal(false, @obj.any?(Float))
  327. assert_equal(false, [1, 42].any?(Float))
  328. assert_equal(true, [1, 4.2].any?(Float))
  329. assert_equal(false, {a: 1, b: 2}.any?(->(kv) { kv == [:foo, 42] }))
  330. assert_equal(true, {a: 1, b: 2}.any?(->(kv) { kv == [:b, 2] }))
  331. end
  332. def test_any_with_unused_block
  333. assert_in_out_err [], <<-EOS, [], ["-:1: warning: given block not used"]
  334. [1, 23].any?(1) {|x| x == 1 }
  335. EOS
  336. assert_in_out_err [], <<-EOS, [], ["-:1: warning: given block not used"]
  337. (1..2).any?(34) {|x| x == 2 }
  338. EOS
  339. assert_in_out_err [], <<-EOS, [], ["-:1: warning: given block not used"]
  340. 3.times.any?(1) {|x| x == 3 }
  341. EOS
  342. assert_in_out_err [], <<-EOS, [], ["-:1: warning: given block not used"]
  343. {a: 1, b: 2}.any?([:b, 2]) {|x| x == 4 }
  344. EOS
  345. end
  346. def test_one
  347. assert(@obj.one? {|x| x == 3 })
  348. assert(!(@obj.one? {|x| x == 1 }))
  349. assert(!(@obj.one? {|x| x == 4 }))
  350. assert(@obj.one?(3..4))
  351. assert(!(@obj.one?(1..2)))
  352. assert(!(@obj.one?(4..5)))
  353. assert(%w{ant bear cat}.one? {|word| word.length == 4})
  354. assert(!(%w{ant bear cat}.one? {|word| word.length > 4}))
  355. assert(!(%w{ant bear cat}.one? {|word| word.length < 4}))
  356. assert(%w{ant bear cat}.one?(/b/))
  357. assert(!(%w{ant bear cat}.one?(/t/)))
  358. assert(!([ nil, true, 99 ].one?))
  359. assert([ nil, true, false ].one?)
  360. assert(![].one?)
  361. assert(!@empty.one?)
  362. assert([ nil, true, 99 ].one?(Integer))
  363. end
  364. def test_one_with_unused_block
  365. assert_in_out_err [], <<-EOS, [], ["-:1: warning: given block not used"]
  366. [1, 2].one?(1) {|x| x == 3 }
  367. EOS
  368. assert_in_out_err [], <<-EOS, [], ["-:1: warning: given block not used"]
  369. (1..2).one?(1) {|x| x == 3 }
  370. EOS
  371. assert_in_out_err [], <<-EOS, [], ["-:1: warning: given block not used"]
  372. 3.times.one?(1) {|x| x == 3 }
  373. EOS
  374. assert_in_out_err [], <<-EOS, [], ["-:1: warning: given block not used"]
  375. {a: 1, b: 2}.one?([:b, 2]) {|x| x == 4 }
  376. EOS
  377. end
  378. def test_none
  379. assert(@obj.none? {|x| x == 4 })
  380. assert(!(@obj.none? {|x| x == 1 }))
  381. assert(!(@obj.none? {|x| x == 3 }))
  382. assert(@obj.none?(4..5))
  383. assert(!(@obj.none?(1..3)))
  384. assert(%w{ant bear cat}.none? {|word| word.length == 5})
  385. assert(!(%w{ant bear cat}.none? {|word| word.length >= 4}))
  386. assert(%w{ant bear cat}.none?(/d/))
  387. assert(!(%w{ant bear cat}.none?(/b/)))
  388. assert([].none?)
  389. assert([nil].none?)
  390. assert([nil,false].none?)
  391. assert(![nil,false,true].none?)
  392. assert(@empty.none?)
  393. end
  394. def test_none_with_unused_block
  395. assert_in_out_err [], <<-EOS, [], ["-:1: warning: given block not used"]
  396. [1, 2].none?(1) {|x| x == 3 }
  397. EOS
  398. assert_in_out_err [], <<-EOS, [], ["-:1: warning: given block not used"]
  399. (1..2).none?(1) {|x| x == 3 }
  400. EOS
  401. assert_in_out_err [], <<-EOS, [], ["-:1: warning: given block not used"]
  402. 3.times.none?(1) {|x| x == 3 }
  403. EOS
  404. assert_in_out_err [], <<-EOS, [], ["-:1: warning: given block not used"]
  405. {a: 1, b: 2}.none?([:b, 2]) {|x| x == 4 }
  406. EOS
  407. end
  408. def test_min
  409. assert_equal(1, @obj.min)
  410. assert_equal(3, @obj.min {|a,b| b <=> a })
  411. cond = ->((a, ia), (b, ib)) { (b <=> a).nonzero? or ia <=> ib }
  412. assert_equal([3, 2], @obj.each_with_index.min(&cond))
  413. enum = %w(albatross dog horse).to_enum
  414. assert_equal("albatross", enum.min)
  415. assert_equal("dog", enum.min {|a,b| a.length <=> b.length })
  416. assert_equal(1, [3,2,1].to_enum.min)
  417. assert_equal(%w[albatross dog], enum.min(2))
  418. assert_equal(%w[dog horse],
  419. enum.min(2) {|a,b| a.length <=> b.length })
  420. assert_equal([13, 14], [20, 32, 32, 21, 30, 25, 29, 13, 14].to_enum.min(2))
  421. assert_equal([2, 4, 6, 7], [2, 4, 8, 6, 7].to_enum.min(4))
  422. end
  423. def test_max
  424. assert_equal(3, @obj.max)
  425. assert_equal(1, @obj.max {|a,b| b <=> a })
  426. cond = ->((a, ia), (b, ib)) { (b <=> a).nonzero? or ia <=> ib }
  427. assert_equal([1, 3], @obj.each_with_index.max(&cond))
  428. enum = %w(albatross dog horse).to_enum
  429. assert_equal("horse", enum.max)
  430. assert_equal("albatross", enum.max {|a,b| a.length <=> b.length })
  431. assert_equal(1, [3,2,1].to_enum.max{|a,b| b <=> a })
  432. assert_equal(%w[horse dog], enum.max(2))
  433. assert_equal(%w[albatross horse],
  434. enum.max(2) {|a,b| a.length <=> b.length })
  435. assert_equal([3, 2], [0, 0, 0, 0, 0, 0, 1, 3, 2].to_enum.max(2))
  436. end
  437. def test_minmax
  438. assert_equal([1, 3], @obj.minmax)
  439. assert_equal([3, 1], @obj.minmax {|a,b| b <=> a })
  440. ary = %w(albatross dog horse)
  441. assert_equal(["albatross", "horse"], ary.minmax)
  442. assert_equal(["dog", "albatross"], ary.minmax {|a,b| a.length <=> b.length })
  443. assert_equal([1, 3], [2,3,1].minmax)
  444. assert_equal([3, 1], [2,3,1].minmax {|a,b| b <=> a })
  445. assert_equal([1, 3], [2,2,3,3,1,1].minmax)
  446. assert_equal([nil, nil], [].minmax)
  447. end
  448. def test_min_by
  449. assert_equal(3, @obj.min_by {|x| -x })
  450. cond = ->(x, i) { -x }
  451. assert_equal([3, 2], @obj.each_with_index.min_by(&cond))
  452. a = %w(albatross dog horse)
  453. assert_equal("dog", a.min_by {|x| x.length })
  454. assert_equal(3, [2,3,1].min_by {|x| -x })
  455. assert_equal(%w[dog horse], a.min_by(2) {|x| x.length })
  456. assert_equal([13, 14], [20, 32, 32, 21, 30, 25, 29, 13, 14].min_by(2) {|x| x})
  457. end
  458. def test_max_by
  459. assert_equal(1, @obj.max_by {|x| -x })
  460. cond = ->(x, i) { -x }
  461. assert_equal([1, 0], @obj.each_with_index.max_by(&cond))
  462. a = %w(albatross dog horse)
  463. assert_equal("albatross", a.max_by {|x| x.length })
  464. assert_equal(1, [2,3,1].max_by {|x| -x })
  465. assert_equal(%w[albatross horse], a.max_by(2) {|x| x.length })
  466. assert_equal([3, 2], [0, 0, 0, 0, 0, 0, 1, 3, 2].max_by(2) {|x| x})
  467. end
  468. def test_minmax_by
  469. assert_equal([3, 1], @obj.minmax_by {|x| -x })
  470. cond = ->(x, i) { -x }
  471. assert_equal([[3, 2], [1, 0]], @obj.each_with_index.minmax_by(&cond))
  472. a = %w(albatross dog horse)
  473. assert_equal(["dog", "albatross"], a.minmax_by {|x| x.length })
  474. assert_equal([3, 1], [2,3,1].minmax_by {|x| -x })
  475. end
  476. def test_member
  477. assert(@obj.member?(1))
  478. assert(!(@obj.member?(4)))
  479. assert([1,2,3].member?(1))
  480. assert(!([1,2,3].member?(4)))
  481. end
  482. class Foo
  483. include Enumerable
  484. def each
  485. yield 1
  486. yield 1,2
  487. end
  488. end
  489. def test_each_with_index
  490. a = []
  491. @obj.each_with_index {|x, i| a << [x, i] }
  492. assert_equal([[1,0],[2,1],[3,2],[1,3],[2,4]], a)
  493. hash = Hash.new
  494. %w(cat dog wombat).each_with_index do |item, index|
  495. hash[item] = index
  496. end
  497. assert_equal({"cat"=>0, "wombat"=>2, "dog"=>1}, hash)
  498. assert_equal([[1, 0], [[1, 2], 1]], Foo.new.each_with_index.to_a)
  499. end
  500. def test_each_with_object
  501. obj = [0, 1]
  502. ret = (1..10).each_with_object(obj) {|i, memo|
  503. memo[0] += i
  504. memo[1] *= i
  505. }
  506. assert_same(obj, ret)
  507. assert_equal([55, 3628800], ret)
  508. assert_equal([[1, nil], [[1, 2], nil]], Foo.new.each_with_object(nil).to_a)
  509. end
  510. def test_each_entry
  511. assert_equal([1, 2, 3], [1, 2, 3].each_entry.to_a)
  512. assert_equal([1, [1, 2]], Foo.new.each_entry.to_a)
  513. a = []
  514. cond = ->(x, i) { a << x }
  515. @obj.each_with_index.each_entry(&cond)
  516. assert_equal([1, 2, 3, 1, 2], a)
  517. end
  518. def test_each_slice
  519. ary = []
  520. (1..10).each_slice(3) {|a| ary << a}
  521. assert_equal([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]], ary)
  522. bug9749 = '[ruby-core:62060] [Bug #9749]'
  523. ary.clear
  524. (1..10).each_slice(3, &lambda {|a, *| ary << a})
  525. assert_equal([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]], ary, bug9749)
  526. ary.clear
  527. (1..10).each_slice(10) {|a| ary << a}
  528. assert_equal([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], ary)
  529. ary.clear
  530. (1..10).each_slice(11) {|a| ary << a}
  531. assert_equal([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], ary)
  532. end
  533. def test_each_cons
  534. ary = []
  535. (1..5).each_cons(3) {|a| ary << a}
  536. assert_equal([[1, 2, 3], [2, 3, 4], [3, 4, 5]], ary)
  537. bug9749 = '[ruby-core:62060] [Bug #9749]'
  538. ary.clear
  539. (1..5).each_cons(3, &lambda {|a, *| ary << a})
  540. assert_equal([[1, 2, 3], [2, 3, 4], [3, 4, 5]], ary, bug9749)
  541. ary.clear
  542. (1..5).each_cons(5) {|a| ary << a}
  543. assert_equal([[1, 2, 3, 4, 5]], ary)
  544. ary.clear
  545. (1..5).each_cons(6) {|a| ary << a}
  546. assert_empty(ary)
  547. end
  548. def test_zip
  549. assert_equal([[1,1],[2,2],[3,3],[1,1],[2,2]], @obj.zip(@obj))
  550. assert_equal([["a",1],["b",2],["c",3]], ["a", "b", "c"].zip(@obj))
  551. a = []
  552. result = @obj.zip([:a, :b, :c]) {|x,y| a << [x, y] }
  553. assert_nil result
  554. assert_equal([[1,:a],[2,:b],[3,:c],[1,nil],[2,nil]], a)
  555. a = []
  556. cond = ->((x, i), y) { a << [x, y, i] }
  557. @obj.each_with_index.zip([:a, :b, :c], &cond)
  558. assert_equal([[1,:a,0],[2,:b,1],[3,:c,2],[1,nil,3],[2,nil,4]], a)
  559. a = []
  560. @obj.zip({a: "A", b: "B", c: "C"}) {|x,y| a << [x, y] }
  561. assert_equal([[1,[:a,"A"]],[2,[:b,"B"]],[3,[:c,"C"]],[1,nil],[2,nil]], a)
  562. ary = Object.new
  563. def ary.to_a; [1, 2]; end
  564. assert_raise(TypeError) {%w(a b).zip(ary)}
  565. def ary.each; [3, 4].each{|e|yield e}; end
  566. assert_equal([[1, 3], [2, 4], [3, nil], [1, nil], [2, nil]], @obj.zip(ary))
  567. def ary.to_ary; [5, 6]; end
  568. assert_equal([[1, 5], [2, 6], [3, nil], [1, nil], [2, nil]], @obj.zip(ary))
  569. obj = eval("class C\u{1f5ff}; self; end").new
  570. assert_raise_with_message(TypeError, /C\u{1f5ff}/) {(1..1).zip(obj)}
  571. end
  572. def test_take
  573. assert_equal([1,2,3], @obj.take(3))
  574. end
  575. def test_take_while
  576. assert_equal([1,2], @obj.take_while {|x| x <= 2})
  577. cond = ->(x, i) {x <= 2}
  578. assert_equal([[1, 0], [2, 1]], @obj.each_with_index.take_while(&cond))
  579. bug5801 = '[ruby-dev:45040]'
  580. @empty.take_while {true}
  581. block = @empty.block
  582. assert_nothing_raised(bug5801) {100.times {block.call}}
  583. end
  584. def test_drop
  585. assert_equal([3,1,2], @obj.drop(2))
  586. end
  587. def test_drop_while
  588. assert_equal([3,1,2], @obj.drop_while {|x| x <= 2})
  589. cond = ->(x, i) {x <= 2}
  590. assert_equal([[3, 2], [1, 3], [2, 4]], @obj.each_with_index.drop_while(&cond))
  591. end
  592. def test_cycle
  593. assert_equal([1,2,3,1,2,1,2,3,1,2], @obj.cycle.take(10))
  594. a = []
  595. @obj.cycle(2) {|x| a << x}
  596. assert_equal([1,2,3,1,2,1,2,3,1,2], a)
  597. a = []
  598. cond = ->(x, i) {a << x}
  599. @obj.each_with_index.cycle(2, &cond)
  600. assert_equal([1,2,3,1,2,1,2,3,1,2], a)
  601. end
  602. def test_callcc
  603. assert_raise(RuntimeError) do
  604. c = nil
  605. @obj.sort_by {|x| callcc {|c2| c ||= c2 }; x }
  606. c.call
  607. end
  608. assert_raise(RuntimeError) do
  609. c = nil
  610. o = Object.new
  611. class << o; self; end.class_eval do
  612. define_method(:<=>) do |x|
  613. callcc {|c2| c ||= c2 }
  614. 0
  615. end
  616. end
  617. [o, o].sort_by {|x| x }
  618. c.call
  619. end
  620. assert_raise(RuntimeError) do
  621. c = nil
  622. o = Object.new
  623. class << o; self; end.class_eval do
  624. define_method(:<=>) do |x|
  625. callcc {|c2| c ||= c2 }
  626. 0
  627. end
  628. end
  629. [o, o, o].sort_by {|x| x }
  630. c.call
  631. end
  632. assert_raise_with_message(RuntimeError, /reentered/) do
  633. i = 0
  634. c = nil
  635. o = Object.new
  636. class << o; self; end.class_eval do
  637. define_method(:<=>) do |x|
  638. callcc {|c2| c ||= c2 }
  639. i += 1
  640. 0
  641. end
  642. end
  643. [o, o].min(1)
  644. assert_operator(i, :<=, 5, "infinite loop")
  645. c.call
  646. end
  647. end
  648. def test_reverse_each
  649. assert_equal([2,1,3,2,1], @obj.reverse_each.to_a)
  650. end
  651. def test_reverse_each_memory_corruption
  652. bug16354 = '[ruby-dev:50867]'
  653. assert_normal_exit %q{
  654. size = 1000
  655. (0...size).reverse_each do |i|
  656. i.inspect
  657. ObjectSpace.each_object(Array) do |a|
  658. a.clear if a.length == size
  659. end
  660. end
  661. }, bug16354
  662. end
  663. def test_chunk
  664. e = [].chunk {|elt| true }
  665. assert_equal([], e.to_a)
  666. e = @obj.chunk {|elt| elt & 2 == 0 ? false : true }
  667. assert_equal([[false, [1]], [true, [2, 3]], [false, [1]], [true, [2]]], e.to_a)
  668. e = @obj.chunk {|elt| elt < 3 ? :_alone : true }
  669. assert_equal([[:_alone, [1]],
  670. [:_alone, [2]],
  671. [true, [3]],
  672. [:_alone, [1]],
  673. [:_alone, [2]]], e.to_a)
  674. e = @obj.chunk {|elt| elt == 3 ? :_separator : true }
  675. assert_equal([[true, [1, 2]],
  676. [true, [1, 2]]], e.to_a)
  677. e = @obj.chunk {|elt| elt == 3 ? nil : true }
  678. assert_equal([[true, [1, 2]],
  679. [true, [1, 2]]], e.to_a)
  680. e = @obj.chunk {|elt| :_foo }
  681. assert_raise(RuntimeError) { e.to_a }
  682. e = @obj.chunk.with_index {|elt, i| elt - i }
  683. assert_equal([[1, [1, 2, 3]],
  684. [-2, [1, 2]]], e.to_a)
  685. assert_equal(4, (0..3).chunk.size)
  686. end
  687. def test_slice_before
  688. e = [].slice_before {|elt| true }
  689. assert_equal([], e.to_a)
  690. e = @obj.slice_before {|elt| elt.even? }
  691. assert_equal([[1], [2,3,1], [2]], e.to_a)
  692. e = @obj.slice_before {|elt| elt.odd? }
  693. assert_equal([[1,2], [3], [1,2]], e.to_a)
  694. ss = %w[abc defg h ijk l mno pqr st u vw xy z]
  695. assert_equal([%w[abc defg h], %w[ijk l], %w[mno], %w[pqr st u vw xy z]],
  696. ss.slice_before(/\A...\z/).to_a)
  697. assert_warning("") {ss.slice_before(/\A...\z/).to_a}
  698. end
  699. def test_slice_after0
  700. assert_raise(ArgumentError) { [].slice_after }
  701. end
  702. def test_slice_after1
  703. e = [].slice_after {|a| flunk "should not be called" }
  704. assert_equal([], e.to_a)
  705. e = [1,2].slice_after(1)
  706. assert_equal([[1], [2]], e.to_a)
  707. e = [1,2].slice_after(3)
  708. assert_equal([[1, 2]], e.to_a)
  709. [true, false].each {|b|
  710. block_results = [true, b]
  711. e = [1,2].slice_after {|a| block_results.shift }
  712. assert_equal([[1], [2]], e.to_a)
  713. assert_equal([], block_results)
  714. block_results = [false, b]
  715. e = [1,2].slice_after {|a| block_results.shift }
  716. assert_equal([[1, 2]], e.to_a)
  717. assert_equal([], block_results)
  718. }
  719. end
  720. def test_slice_after_both_pattern_and_block
  721. assert_raise(ArgumentError) { [].slice_after(1) {|a| true } }
  722. end
  723. def test_slice_after_continuation_lines
  724. lines = ["foo\n", "bar\\\n", "baz\n", "\n", "qux\n"]
  725. e = lines.slice_after(/[^\\]\n\z/)
  726. assert_equal([["foo\n"], ["bar\\\n", "baz\n"], ["\n", "qux\n"]], e.to_a)
  727. end
  728. def test_slice_before_empty_line
  729. lines = ["foo", "", "bar"]
  730. e = lines.slice_after(/\A\s*\z/)
  731. assert_equal([["foo", ""], ["bar"]], e.to_a)
  732. end
  733. def test_slice_when_0
  734. e = [].slice_when {|a, b| flunk "should not be called" }
  735. assert_equal([], e.to_a)
  736. end
  737. def test_slice_when_1
  738. e = [1].slice_when {|a, b| flunk "should not be called" }
  739. assert_equal([[1]], e.to_a)
  740. end
  741. def test_slice_when_2
  742. e = [1,2].slice_when {|a,b|
  743. assert_equal(1, a)
  744. assert_equal(2, b)
  745. true
  746. }
  747. assert_equal([[1], [2]], e.to_a)
  748. e = [1,2].slice_when {|a,b|
  749. assert_equal(1, a)
  750. assert_equal(2, b)
  751. false
  752. }
  753. assert_equal([[1, 2]], e.to_a)
  754. end
  755. def test_slice_when_3
  756. block_invocations = [
  757. lambda {|a, b|
  758. assert_equal(1, a)
  759. assert_equal(2, b)
  760. true
  761. },
  762. lambda {|a, b|
  763. assert_equal(2, a)
  764. assert_equal(3, b)
  765. false
  766. }
  767. ]
  768. e = [1,2,3].slice_when {|a,b|
  769. block_invocations.shift.call(a, b)
  770. }
  771. assert_equal([[1], [2, 3]], e.to_a)
  772. assert_equal([], block_invocations)
  773. end
  774. def test_slice_when_noblock
  775. assert_raise(ArgumentError) { [].slice_when }
  776. end
  777. def test_slice_when_contiguously_increasing_integers
  778. e = [1,4,9,10,11,12,15,16,19,20,21].slice_when {|i, j| i+1 != j }
  779. assert_equal([[1], [4], [9,10,11,12], [15,16], [19,20,21]], e.to_a)
  780. end
  781. def test_chunk_while_contiguously_increasing_integers
  782. e = [1,4,9,10,11,12,15,16,19,20,21].chunk_while {|i, j| i+1 == j }
  783. assert_equal([[1], [4], [9,10,11,12], [15,16], [19,20,21]], e.to_a)
  784. end
  785. def test_detect
  786. @obj = ('a'..'z')
  787. assert_equal('c', @obj.detect {|x| x == 'c' })
  788. proc = Proc.new {|x| x == 'c' }
  789. assert_equal('c', @obj.detect(&proc))
  790. lambda = ->(x) { x == 'c' }
  791. assert_equal('c', @obj.detect(&lambda))
  792. assert_equal(['c',2], @obj.each_with_index.detect {|x, i| x == 'c' })
  793. proc2 = Proc.new {|x, i| x == 'c' }
  794. assert_equal(['c',2], @obj.each_with_index.detect(&proc2))
  795. bug9605 = '[ruby-core:61340]'
  796. lambda2 = ->(x, i) { x == 'c' }
  797. assert_equal(['c',2], @obj.each_with_index.detect(&lambda2), bug9605)
  798. end
  799. def test_select
  800. @obj = ('a'..'z')
  801. assert_equal(['c'], @obj.select {|x| x == 'c' })
  802. proc = Proc.new {|x| x == 'c' }
  803. assert_equal(['c'], @obj.select(&proc))
  804. lambda = ->(x) { x == 'c' }
  805. assert_equal(['c'], @obj.select(&lambda))
  806. assert_equal([['c',2]], @obj.each_with_index.select {|x, i| x == 'c' })
  807. proc2 = Proc.new {|x, i| x == 'c' }
  808. assert_equal([['c',2]], @obj.each_with_index.select(&proc2))
  809. bug9605 = '[ruby-core:61340]'
  810. lambda2 = ->(x, i) { x == 'c' }
  811. assert_equal([['c',2]], @obj.each_with_index.select(&lambda2), bug9605)
  812. end
  813. def test_map
  814. @obj = ('a'..'e')
  815. assert_equal(['A', 'B', 'C', 'D', 'E'], @obj.map {|x| x.upcase })
  816. proc = Proc.new {|x| x.upcase }
  817. assert_equal(['A', 'B', 'C', 'D', 'E'], @obj.map(&proc))
  818. lambda = ->(x) { x.upcase }
  819. assert_equal(['A', 'B', 'C', 'D', 'E'], @obj.map(&lambda))
  820. assert_equal([['A',0], ['B',1], ['C',2], ['D',3], ['E',4]],
  821. @obj.each_with_index.map {|x, i| [x.upcase, i] })
  822. proc2 = Proc.new {|x, i| [x.upcase, i] }
  823. assert_equal([['A',0], ['B',1], ['C',2], ['D',3], ['E',4]],
  824. @obj.each_with_index.map(&proc2))
  825. lambda2 = ->(x, i) { [x.upcase, i] }
  826. assert_equal([['A',0], ['B',1], ['C',2], ['D',3], ['E',4]],
  827. @obj.each_with_index.map(&lambda2))
  828. hash = { a: 'hoge', b: 'fuga' }
  829. lambda = -> (k, v) { "#{k}:#{v}" }
  830. assert_equal ["a:hoge", "b:fuga"], hash.map(&lambda)
  831. end
  832. def test_flat_map
  833. @obj = [[1,2], [3,4]]
  834. assert_equal([2,4,6,8], @obj.flat_map {|i| i.map{|j| j*2} })
  835. proc = Proc.new {|i| i.map{|j| j*2} }
  836. assert_equal([2,4,6,8], @obj.flat_map(&proc))
  837. lambda = ->(i) { i.map{|j| j*2} }
  838. assert_equal([2,4,6,8], @obj.flat_map(&lambda))
  839. assert_equal([[1,2],0,[3,4],1],
  840. @obj.each_with_index.flat_map {|x, i| [x,i] })
  841. proc2 = Proc.new {|x, i| [x,i] }
  842. assert_equal([[1,2],0,[3,4],1],
  843. @obj.each_with_index.flat_map(&proc2))
  844. lambda2 = ->(x, i) { [x,i] }
  845. assert_equal([[1,2],0,[3,4],1],
  846. @obj.each_with_index.flat_map(&lambda2))
  847. end
  848. def assert_typed_equal(e, v, cls, msg=nil)
  849. assert_kind_of(cls, v, msg)
  850. assert_equal(e, v, msg)
  851. end
  852. def assert_int_equal(e, v, msg=nil)
  853. assert_typed_equal(e, v, Integer, msg)
  854. end
  855. def assert_rational_equal(e, v, msg=nil)
  856. assert_typed_equal(e, v, Rational, msg)
  857. end
  858. def assert_float_equal(e, v, msg=nil)
  859. assert_typed_equal(e, v, Float, msg)
  860. end
  861. def assert_complex_equal(e, v, msg=nil)
  862. assert_typed_equal(e, v, Complex, msg)
  863. end
  864. def test_sum
  865. class << (enum = Object.new)
  866. include Enumerable
  867. def each
  868. yield 3
  869. yield 5
  870. yield 7
  871. end
  872. end
  873. assert_int_equal(15, enum.sum)
  874. assert_int_equal(0, [].each.sum)
  875. assert_int_equal(3, [3].each.sum)
  876. assert_int_equal(8, [3, 5].each.sum)
  877. assert_int_equal(15, [3, 5, 7].each.sum)
  878. assert_rational_equal(8r, [3, 5r].each.sum)
  879. assert_float_equal(15.0, [3, 5, 7.0].each.sum)
  880. assert_float_equal(15.0, [3, 5r, 7.0].each.sum)
  881. assert_complex_equal(8r + 1i, [3, 5r, 1i].each.sum)
  882. assert_complex_equal(15.0 + 1i, [3, 5r, 7.0, 1i].each.sum)
  883. assert_int_equal(2*FIXNUM_MAX, Array.new(2, FIXNUM_MAX).each.sum)
  884. assert_int_equal(2*(FIXNUM_MAX+1), Array.new(2, FIXNUM_MAX+1).each.sum)
  885. assert_int_equal(10*FIXNUM_MAX, Array.new(10, FIXNUM_MAX).each.sum)
  886. assert_int_equal(0, ([FIXNUM_MAX, 1, -FIXNUM_MAX, -1]*10).each.sum)
  887. assert_int_equal(FIXNUM_MAX*10, ([FIXNUM_MAX+1, -1]*10).each.sum)
  888. assert_int_equal(2*FIXNUM_MIN, Array.new(2, FIXNUM_MIN).each.sum)
  889. assert_float_equal(0.0, [].each.sum(0.0))
  890. assert_float_equal(3.0, [3].each.sum(0.0))
  891. assert_float_equal(3.5, [3].each.sum(0.5))
  892. assert_float_equal(8.5, [3.5, 5].each.sum)
  893. assert_float_equal(10.5, [2, 8.5].each.sum)
  894. assert_float_equal((FIXNUM_MAX+1).to_f, [FIXNUM_MAX, 1, 0.0].each.sum)
  895. assert_float_equal((FIXNUM_MAX+1).to_f, [0.0, FIXNUM_MAX+1].each.sum)
  896. assert_rational_equal(3/2r, [1/2r, 1].each.sum)
  897. assert_rational_equal(5/6r, [1/2r, 1/3r].each.sum)
  898. assert_equal(2.0+3.0i, [2.0, 3.0i].each.sum)
  899. assert_int_equal(13, [1, 2].each.sum(10))
  900. assert_int_equal(16, [1, 2].each.sum(10) {|v| v * 2 })
  901. yielded = []
  902. three = SimpleDelegator.new(3)
  903. ary = [1, 2.0, three]
  904. assert_float_equal(12.0, ary.each.sum {|x| yielded << x; x * 2 })
  905. assert_equal(ary, yielded)
  906. assert_raise(TypeError) { [Object.new].each.sum }
  907. large_number = 100000000
  908. small_number = 1e-9
  909. until (large_number + small_number) == large_number
  910. small_number /= 10
  911. end
  912. assert_float_equal(large_number+(small_number*10), [large_number, *[small_number]*10].each.sum)
  913. assert_float_equal(large_number+(small_number*10), [large_number/1r, *[small_number]*10].each.sum)
  914. assert_float_equal(large_number+(small_number*11), [small_number, large_number/1r, *[small_number]*10].each.sum)
  915. assert_float_equal(small_number, [large_number, small_number, -large_number].each.sum)
  916. k = Class.new do
  917. include Enumerable
  918. def initialize(*values)
  919. @values = values
  920. end
  921. def each(&block)
  922. @values.each(&block)
  923. end
  924. end
  925. assert_equal(+Float::INFINITY, k.new(0.0, +Float::INFINITY).sum)
  926. assert_equal(+Float::INFINITY, k.new(+Float::INFINITY, 0.0).sum)
  927. assert_equal(-Float::INFINITY, k.new(0.0, -Float::INFINITY).sum)
  928. assert_equal(-Float::INFINITY, k.new(-Float::INFINITY, 0.0).sum)
  929. assert_predicate(k.new(-Float::INFINITY, Float::INFINITY).sum, :nan?)
  930. assert_equal("abc", ["a", "b", "c"].each.sum(""))
  931. assert_equal([1, [2], 3], [[1], [[2]], [3]].each.sum([]))
  932. end
  933. def test_hash_sum
  934. histogram = { 1 => 6, 2 => 4, 3 => 3, 4 => 7, 5 => 5, 6 => 4 }
  935. assert_equal(100, histogram.sum {|v, n| v * n })
  936. end
  937. def test_range_sum
  938. assert_int_equal(55, (1..10).sum)
  939. assert_float_equal(55.0, (1..10).sum(0.0))
  940. assert_int_equal(90, (5..10).sum {|v| v * 2 })
  941. assert_float_equal(90.0, (5..10).sum(0.0) {|v| v * 2 })
  942. assert_int_equal(0, (2..0).sum)
  943. assert_int_equal(5, (2..0).sum(5))
  944. assert_int_equal(2, (2..2).sum)
  945. assert_int_equal(42, (2...2).sum(42))
  946. not_a_range = Class.new do
  947. include Enumerable # Defines the `#sum` method
  948. def each
  949. yield 2
  950. yield 4
  951. yield 6
  952. end
  953. def begin; end
  954. def end; end
  955. end
  956. assert_equal(12, not_a_range.new.sum)
  957. end
  958. def test_uniq
  959. src = [1, 1, 1, 1, 2, 2, 3, 4, 5, 6]
  960. assert_equal([1, 2, 3, 4, 5, 6], src.uniq.to_a)
  961. olympics = {
  962. 1896 => 'Athens',
  963. 1900 => 'Paris',
  964. 1904 => 'Chicago',
  965. 1906 => 'Athens',
  966. 1908 => 'Rome',
  967. }
  968. assert_equal([[1896, "Athens"], [1900, "Paris"], [1904, "Chicago"], [1908, "Rome"]],
  969. olympics.uniq{|k,v| v})
  970. assert_equal([1, 2, 3, 4, 5, 10], (1..100).uniq{|x| (x**2) % 10 }.first(6))
  971. assert_equal([1, [1, 2]], Foo.new.to_enum.uniq)
  972. end
  973. def test_transient_heap_sort_by
  974. klass = Class.new do
  975. include Comparable
  976. attr_reader :i
  977. def initialize e
  978. @i = e
  979. end
  980. def <=> other
  981. GC.start
  982. i <=> other.i
  983. end
  984. end
  985. assert_equal [1, 2, 3, 4, 5], (1..5).sort_by{|e| klass.new e}
  986. end
  987. def test_filter_map
  988. @obj = (1..8).to_a
  989. assert_equal([4, 8, 12, 16], @obj.filter_map { |i| i * 2 if i.even? })
  990. assert_equal([2, 4, 6, 8, 10, 12, 14, 16], @obj.filter_map { |i| i * 2 })
  991. assert_equal([0, 0, 0, 0, 0, 0, 0, 0], @obj.filter_map { 0 })
  992. assert_equal([], @obj.filter_map { false })
  993. assert_equal([], @obj.filter_map { nil })
  994. assert_instance_of(Enumerator, @obj.filter_map)
  995. end
  996. end