簡體   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