繁体   English   中英

Ruby:枚举的最大值抛出`ArgumentError:参数数量错误(给定1,预期为0)`

[英]Ruby: max of enumerize throw `ArgumentError: wrong number of arguments (given 1, expected 0)`

例如,我们有一个类。

class Foo
  def initialize(a)
    @a = a
  end

  def a
    @a
  end
end

我们像这样使用它

[Foo.new(1), Foo.new(2)].max(&:a)
=> ArgumentError: wrong number of arguments (given 1, expected 0)

[Foo.new(1), Foo.new(2)].max { |e| e.a }

工作正常。

为什么?

# ruby doc for Array (https://ruby-doc.org/core-2.7.1/Array.html#method-i-max)
max → obj
max {|a, b| block} → obj

[Foo.new(1), Foo.new(2)].max(&:a)
匹配第一个没有参数的“max”。

[Foo.new(1), Foo.new(2)].max { |e| ea }
第二个使用块返回 a <=> b。

[Foo.new(3), Foo.new(2)].max { |e| e.a }
# would not get the expect result

数组的max引用

max_foo = [Foo.new(1), Foo.new(2)].max { |c, d| c.a <=> d.a } 
max_foo.inspect # will return max array element after comparing something like #<Foo:0x00007fe3cb84e318 @a=2>
max_foo.a # will return 2

在单行

max_foo = [Foo.new(1), Foo.new(2)].map(&:a).max # Will return 2

下面详细解释max方法

  1. 块 {|a, b| block} Returns the object in ary with the maximum value. The first form assumes all objects implement Comparable; the second uses the block to return a <=> b. Returns the object in ary with the maximum value. The first form assumes all objects implement Comparable; the second uses the block to return a <=> b.

     2.6.5 :030 > %w(gzabc def ghi abcdef).max {|a,b| a.length <=> b.length } => "abcdef"
  2. 没有任何参数或块,返回数组的最大element

     2.6.5 :021 > (4..9).to_a.max => 9 2.6.5 :022 > [500, 200, 150, 300].max => 500 2.6.5 :023 > [1,2,3,9,8,7,4,5,6].max => 9 2.6.5 :027 > %w(gzabc def ghi abc).max => "gzabc"
  3. Number n If the n argument is given, maximum n elements are returned as an array.

     2.6.5 :011 > (4..9).to_a.max(2) # Returns first two max values from given `n` ie 2 here => [9, 8] 2.6.5 :012 > [1,2,3,9,8,7,4,5,6].max(3) # Returns first three max values from given `n` ie 3 here => [9, 8, 7] 2.6.5 :013 > [500, 200, 150, 300].max(1) # Even if the value of `n` is 1 it will return array => [500] 2.6.5 :014 > [500, 200, 150, 300].max(0) => [] 2.6.5 :028 > %w(gzabc def ghi abc).max(2) => ["gzabc", "ghi"]
[Foo.new(1), Foo.new(2)].max { |e| ea }

工作正常。

不,它没有。 当您的输入不是严格按升序排列时(例如[Foo.new(3), Foo.new(2)][Foo.new(3), Foo.new(2)]它可能会返回错误的值。

块到max将被赋予两个参数,它应该<=>它们。

你是说.max_by(&:a)吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM