[ruby-talk:02438] Re: Arrays and ranges

From: Dave Thomas <Dave@...>
Date: 2000-04-10 23:09:45 UTC
List: ruby-talk #2438
h.fulton@att.net writes:

> a=Array(1..5)
> b=1..5
> c=[1..5]
> d=[1,2,3,4,5];
> 
> if c=d
>   print "c and d are the same\n"
> else
>   print "c and d are NOT the same\n"
> end
> # Above: Confirms that c and d are the same

Actually, it doesn't ;-) You've got an assignment in the condition to
the if statement, so the value will we true regardless of the
relationship between c and d (unless d is nil or false).

If you compile with ruby -w, you'd get

  -:10: warning: assignment in condition
  c and d are the same

The assignment 'c = [1..5]' creates an array containing a single
element. That element is an object of type Range.

If you want to populate the array from a range, you could use

  a = (1..5).to_a (or see below)

This is reasonable -- a range is an object, rather than an
abbreviation for an array. Ruby in this case is being remarkably
transparent: an object is an object is an object, so

  a = [ 1..5 ]

is treated no differently than

  a = [ /^cat/ ]

or

  a = [ 3.14159 ]


The strangeness comes from the handling of

  a = Array(1..5)

This is because of a bit of magic in class Object. The word 'Array' in
the above line is not a reference to class Array. Instead, it's a
global function (a class method of Kernel) that takes its parameter,
run's 'to_a' on it, and uses the result to create an array. Thus

  a = Array(1..5)

is the same as

  a = Array.new((1..5).to_a)

There are similar global functions for Integer, Float, and String.

Regards


Dave

In This Thread

Prev Next