Project

General

Profile

Actions

Bug #20911

closed

Array#max doesn't take block if using &:

Added by alvitovitch@gmail.com (Andrew Vitovitch) 8 months ago. Updated 8 months ago.

Status:
Rejected
Assignee:
-
Target version:
-
ruby -v:
ruby 3.3.5
[ruby-core:120014]

Description

["1","2","3"].max { |i| i.to_i }

=> "3"


["1","2","3"].max(&:to_i)

(irb):6:in `to_i': no implicit conversion of String into Integer (TypeError)

["1","2","3"].max(&:to_i)
                  ^^^^^^
	from (irb):6:in `max'
	from (irb):6:in `<main>'
	from <internal:kernel>:187:in `loop'
	from /Users/alvitovitch/.asdf/installs/ruby/3.3.5/lib/ruby/gems/3.3.0/gems/irb-1.13.1/exe/irb:9:in `<top (required)>'
	from /Users/alvitovitch/.asdf/installs/ruby/3.3.5/bin/irb:25:in `load'
	from /Users/alvitovitch/.asdf/installs/ruby/3.3.5/bin/irb:25:in `<main>'

Updated by mame (Yusuke Endoh) 8 months ago

  • Status changed from Open to Rejected

Array#max accepts a block that compares two values.

p ["1", "2", "3"].max {|i, j| i.to_i <=> j.to_i } #=> "3"

You may want to use Array#max_by.

p ["1", "2", "3"].max_by(&:to_i) #=> "3"
Actions #2

Updated by nobu (Nobuyoshi Nakada) 8 months ago

  • Description updated (diff)
Actions

Also available in: Atom PDF

Like0
Like0Like0