列表元素比较中Ruby 1.8与1.9之间的差异

时间:2012-10-29 00:48:18

标签: ruby list ruby-1.9 ruby-1.8

两个Ruby版本是:1.8.7(学校使用)和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 个答案:

答案 0 :(得分:0)

  

尝试def odd_one_out_in_list?(list); list.uniq.size == 1;结束。更简单,可能更快