【问题标题】:Why would this code cause: ArgumentError comparison of Array with Array failed为什么此代码会导致:ArgumentError Array 与 Array 的比较失败
【发布时间】:2017-04-20 15:31:04
【问题描述】:

这里是 Ruby 初学者。最近碰到这个问题:

我的朋友约翰和我是“Fat to Fit Club (FFC)”的成员。 John 很担心,因为每个月都会发布一个包含成员权重的列表,并且每个月他都是列表中的最后一个,这意味着他是最重的。 我是建立名单的人,所以我告诉他:“别担心,我会修改名单的顺序”。决定将“权重”归因于数字。从现在开始,一个数字的权重将是其数字的总和。 例如,99 的“权重”为 18,100 的“权重”为 1,因此在列表中 100 将排在 99 之前。给定一个具有 FFC 成员权重的字符串以正常顺序排列,您可以给该字符串按“权重”排序吗?这些数字?

我试图解决这个问题:

def order_weight(strng)
  new_strng = strng.split(" ").map! {|x| x.split(//)}.map! {|x| x.reduce {|sum, input| sum.to_i + input.to_i}}
  output = strng.split(" ").zip(new_strng)
  output.sort_by! {|x, y| [y, x]}
  output.reduce("") {|memo, input| memo << input[0] + " "}.chop
end

order_weight("2000 10003 1234000 44444444 9999 11 11 22 123") 
#=> "11 11 2000 10003 22 123 1234000 44444444 9999"

这似乎工作正常(如果有更简单的方法请告诉我)但我的问题是我收到: #&lt;ArgumentError: comparison of Array with Array failed&gt;

我已经阅读了一些内容,发现这个问题可能是由于将 nil 值与 Enumerable#sort_by 进行比较而引起的,但据我所知,这里不应该是这种情况(?)

任何帮助将不胜感激

【问题讨论】:

  • 每当您报告异常时,请包括引发异常的行。您还需要展示string 的外观。
  • 我想我应该包含的另一条信息是,我只有在通过这些问题来自的网站(codewars)输入我的代码时才会收到此错误。这是一张图片来说明我的意思imgur.com/a/aqRkP
  • 别忘了有一个编辑按钮供您使用。

标签: ruby sorting enumerable


【解决方案1】:

假设成员的权重如下。

weights = { "Bubba"=>302, "Phil"=>139, "Hubert"=>280 }

那么你可以做以下事情。

puts weights.sort_by { |k,v| v.to_s.each_char.reduce(0) { |t,s| t+s.to_i } }.
  map { |a| a.join(" ") }.
  join("\n")
  # Bubba 302
  # Hubert 280
  # Phil 139

步骤如下。

a = weights.sort_by { |k,v| v.to_s.each_char.reduce(0) { |t,s| t+s.to_i } }
  #=> [["Bubba", 302], ["Hubert", 280], ["Phil", 139]] 
b = a.map { |a| a.join(" ") }
  #=> ["Bubba 302", "Hubert 280", "Phil 139"] 
c = b.join("\n")
  #=> "Bubba 302\nHubert 280\nPhil 139" 
puts c
  # Bubba 302
  # Hubert 280
  # Phil 139

在计算a 我们有

enum = weights.sort_by
  #=> #<Enumerator: {"Bubba"=>302, "Phil"=>139, "Hubert"=>280}:sort_by>

enum 生成的第一个元素被传递给块并使用并行赋值分配给块变量。

k, v = enum.next
  #=> ["Bubba", 302] 
k #=> "Bubba"
v #=> 302 

块计算如下。

d = v.to_s
  # => "302" 
d.each_char.reduce(0) { |t,s| t+s.to_i }
  #=> 5

enum 的其余两个元素的计算类似。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 2017-09-18
    • 1970-01-01
    • 2014-02-01
    • 2017-01-31
    • 1970-01-01
    相关资源
    最近更新 更多