[英]Can't figure out what the error is with this method?
I'm passing a hash to this function that either a) has keys that are strings along with values that are ints OR b) it is an empty hash. 我向此函数传递了一个散列,该散列是:a)具有作为字符串的键以及带有整数的值,或者b)它是一个空散列。 The point of the function is to return nil if the hash is empty and return the key associated with the lowest int.
该函数的重点是,如果散列为空,则返回nil,并返回与最低int关联的键。
def key_for_min_value(name_hash)
if name_hash == nil
return nil
else
lowest_value = nil
lowest_value_name = nil
name_hash.collect do |name, value|
if lowest_value > value
lowest_value = value
lowest_value_name = name
end
end
return lowest_value_name
end
end
The error I'm receiving is: 我收到的错误是:
1) smallest hash value does not call the `#keys` method
Failure/Error: key_for_min_value(hash)
NoMethodError:
undefined method `>' for nil:NilClass`
You can't compare nil
to anything using >
, it's not allowed, so you either have to avoid that test or use tools like min_by
to get the right value instead of this collect
approach. 您不能使用
>
将nil
与任何内容进行比较,这是不允许的,因此您必须避免进行该测试,或者使用min_by
工具来获取正确的值,而不是使用这种collect
方法。
One way to make your unit test happy might be: 使单元测试满意的一种方法可能是:
def key_for_min_value(name_hash)
return unless (name_hash)
name_hash.keys.min_by do |key|
name_hash[key]
end
end
Ruby leans very heavily on the Enumerable library, there's a tool in there for nearly every job, so when you have some free time have a look around there, lots of things to discover. Ruby非常依赖Enumerable库,那里几乎有每项工作都有一个工具,因此当您有空闲时间时,可以看看那里很多东西。
Now Ruby is very strict about comparisons, and in particular a nil
value can't be "compared" (eg >
or <
and such) to other values. 现在,Ruby对比较非常严格,尤其是不能将
nil
值与其他值“比较”(例如>
或<
等)。 You'll need to populate that minimum with the first value by default, not nil
, then the comparisons work out, but doing that completely is pretty ugly: 默认情况下,您需要使用第一个值而不是
nil
来填充最小值,然后进行比较,但是完全做到这一点非常难看:
def key_for_min_value(name_hash)
return unless (name_hash)
min_key, min_value = name_hash.first
name_hash.each do |key, value|
next unless (value < min_value)
min_key = key
min_value = value
end
min_key
end
So that approach is really not worth it. 因此,这种方法确实不值得。 Enumerable makes it way easier and as a bonus your intent is clear.
枚举使得它比较容易的方式 ,并作为奖励你的意图是明确的。 One thing you'll come to appreciate is that in Ruby if your code looks like code then you're probably going about it the wrong way, over-complicating things.
您将欣赏的一件事是,在Ruby中,如果您的代码看起来像代码,那么您可能会以错误的方式进行操作,从而使事情变得过于复杂。
Ruby is an unusually expressive language, and often there's a very minimal form to express just about anything. Ruby是一种异常表达的语言,通常有一种非常简单的形式可以表达几乎所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.