10

I recently started learning Ruby and i'm reading the following Ruby Manual.

In this manual they say the following (about Ranges):

A final use of the versatile range is as an interval test: seeing if some value falls within the interval represented by the range. This is done using ===, the case equality operator.

With these examples:

  • (1..10) === 5 » true
  • (1..10) === 15 » false
  • (1..10) === 3.14159 » true
  • ('a'..'j') === 'c' » true
  • ('a'..'j') === 'z' » false

After read about the Ruby "===" operator here, I found that this works on ranges because Ruby translates this to case statement.

So you may want to be able to put the range in your case statement, and have it be selected. Also, note that case statements translate to b===a in statements like case a when b then true end.

However I have the following question: why does the following command return true?

(1..10) === 3.14159 » true

Since (1..10) means [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], I expected that the result would be false.

4

1 に答える 1

11

1..10Rangeは数学的な意味で 0 から 10 を示し、したがって含まれます。3.14259

と同じではありません[1,2,3,4,5,6,7,8,9,10]

この配列は、 オブジェクトの配列表現を構築するRange#eachために によって使用されるメソッド の結果でありEnumerable#to_a、Range に含まれる整数値のみを生成します。これは、すべての実数値を生成することは無限の数の要素をトラバースすることを意味するためです。

于 2012-12-05T15:20:15.277 に答える