如何将范围与数组进行比较?

时间:2014-10-07 05:59:41

标签: ruby

如何查看数组是否与范围匹配?

[1..3] == [1,2,3] # => false

我也试过

[1..3].to_a == [1,2,3] # => false

但是我很难过。有没有办法将范围强制转换为数组,以便将其与一个数组进行比较?

2 个答案:

答案 0 :(得分:3)

啊!事实证明我对语法感到困惑。

arr = [1..3] # Actually sets an array with a range as the first element
arr[0] # => 1..3

我需要的是:

(1..3).to_a == [1,2,3] # => true

答案 1 :(得分:1)

2.1.1 :006 > [1..3].class
 => Array 
2.1.1 :007 > (1..3).class
 => Range 
2.1.1 :008 > (1..3).to_a == [1,2,3]
 => true 

希望能解决您的问题