Project

General

Profile

Actions

Bug #18953

closed

`Array#uniq` doesn't evaluate the given block when the size of the array is one

Added by ttanimichi (Tsukuru Tanimichi) over 2 years ago. Updated over 2 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
ruby -v:
ruby 3.1.2p20 (2022-04-12 revision 4491bb740a) [arm64-darwin21]
[ruby-dev:51189]

Description

Array#uniq doesn't evaluate the given block when the size of the array is one. Is this expected behavior?

$ ruby -e '[42, 43].uniq { _1.foo }; puts true'
-e:1:in `block in <main>': undefined method `foo' for 42:Integer (NoMethodError)

[42, 43].uniq { _1.foo }; puts true
                  ^^^^
Did you mean?  floor
	from -e:1:in `uniq'
	from -e:1:in `<main>'
$ ruby -e '[42].uniq { _1.foo }; puts true'
true

Updated by mrkn (Kenta Murata) over 2 years ago

I hope this behavior should be expected.
However, sort_by, max_by, and min_by call the given blocks even if the receiver array has only one item.

irb(main):001:0> [42].sort_by { _1.foo }
(irb):1:in `block in <top (required)>': undefined method `foo' for 42:Integer (NoMethodError)
Did you mean?  floor
	from (irb):1:in `each'
	from (irb):1:in `sort_by'
	from (irb):1:in `<main>'
	from /home/mrkn/.rbenv/versions/3.1.0/lib/ruby/gems/3.1.0/gems/irb-1.4.1/exe/irb:11:in `<top (required)>'
	from /home/mrkn/.rbenv/versions/3.1.0/bin/irb:25:in `load'
	from /home/mrkn/.rbenv/versions/3.1.0/bin/irb:25:in `<main>'
irb(main):002:0> [42].max_by { _1.foo }
(irb):2:in `block in <top (required)>': undefined method `foo' for 42:Integer (NoMethodError)
Did you mean?  floor
	from (irb):2:in `each'
	from (irb):2:in `max_by'
	from (irb):2:in `<main>'
	from /home/mrkn/.rbenv/versions/3.1.0/lib/ruby/gems/3.1.0/gems/irb-1.4.1/exe/irb:11:in `<top (required)>'
	from /home/mrkn/.rbenv/versions/3.1.0/bin/irb:25:in `load'
	from /home/mrkn/.rbenv/versions/3.1.0/bin/irb:25:in `<main>'
irb(main):003:0> [42].min_by { _1.foo }
(irb):3:in `block in <top (required)>': undefined method `foo' for 42:Integer (NoMethodError)
Did you mean?  floor
	from (irb):3:in `each'
	from (irb):3:in `min_by'
	from (irb):3:in `<main>'
	from /home/mrkn/.rbenv/versions/3.1.0/lib/ruby/gems/3.1.0/gems/irb-1.4.1/exe/irb:11:in `<top (required)>'
	from /home/mrkn/.rbenv/versions/3.1.0/bin/irb:25:in `load'
	from /home/mrkn/.rbenv/versions/3.1.0/bin/irb:25:in `<main>'

Updated by nobu (Nobuyoshi Nakada) over 2 years ago

I think this is an expected behavior, but an implementation detail.

Actions #3

Updated by jeremyevans0 (Jeremy Evans) over 2 years ago

  • Status changed from Open to Rejected
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0