【发布时间】:2012-10-29 00:48:18
【问题描述】:
两个 Ruby 版本是:1.8.7(学校使用)vs. 1.9.3(当前版本,我的系统上有)。
只是好奇 1.9.3 中有什么不同导致以下内容无法正常工作。如果列表中的所有元素都相同,则该函数输出true,如果不完全相同,则输出false。
e.g.
[1,1,1] => true
[1,2,1] => false
在 Ruby 1.9.4 中,
odd_one_out_in_list?([1,1,1])
=> false #which is should output 'true'
在 Ruby 1.8.7 中,
odd_one_out_in_list?([1,1,1])
=> true #which is good
下面的逻辑在我看来没问题。 1.9.4 有什么不同?我已经签出: What is the difference between Ruby 1.8 and Ruby 1.9 但我无法在那里找到答案。
这是我的功能:
def odd_one_out_in_list?(list)
sorted_list = list.sort
if sorted_list[0] == sorted_list[list.length-1]
return true
else
return false
end
end
【问题讨论】:
-
另外,我无法重现这个。对于您提供的输入,1.8.7 和 1.9.3 给我相同的结果。
-
为什么不直接返回比较结果呢?
-
试试
def odd_one_out_in_list?(list); list.uniq.size == 1; end。更简单,可能更快。
标签: ruby list ruby-1.9 ruby-1.8