[#3986] Re: Principle of least effort -- another Ruby virtue. — Andrew Hunt <andy@...>

> Principle of Least Effort.

14 messages 2000/07/14

[#4043] What are you using Ruby for? — Dave Thomas <Dave@...>

16 messages 2000/07/16

[#4139] Facilitating Ruby self-propagation with the rig-it autopolymorph application. — Conrad Schneiker <schneik@...>

Hi,

11 messages 2000/07/20

[ruby-talk:03839] *arr expansion

From: hal9000@...
Date: 2000-07-05 16:19:36 UTC
List: ruby-talk #3839
I'm having a little problem here.

I've pared the code down to something small enough
to show what's happening.

As I understand it, when an asterisk is used before
an argument in a method definition, it means an arbitrary
number of values.

  def foo(*args) # args is really a sequence of values

When it's used with an array in a method call, it means to
expand the array into a list of values.

  foo(*arr) # Means same as foo(arr[0], arr[1], arr[2], ...)

Have I said anything wrong so far?

Now... in the code below, I expect this output:

  [ 1, 2, 3, 4 ]
  [ 3, 4 ]
  [ 1, 2 ]
  2

But I get:

  [ 1, 2, 3, 4 ]
  [ 3, 4 ]
  [ 12 ]
  1

Notice the line that I've marked "line A." It's a surprise
to me that the code behaves the same with or without the
asterisk.

Help?

Hal

------------------------

def Set(*elts)
  Set.new(elts)
end

class Set

  attr_accessor :elts

  def initialize(*elts)
    @elts = Array.new;
    elts.each {|x| @elts << x}
    @elts.uniq!
  end

  def -(other)
    Set(*(@elts - other.elts))    ### line A
  end

  def inspect
    s=""
    @elts.each_index { |x|
      z = @elts[x].to_s
      case x
        when 0
          s += "[ "+z+(@elts.size>1?", ":"")
        when 1..(@elts.size-2)
          s += z+", "
        when (@elts.size-1)
          s += z
      end
    }
    s+" ]"
  end

  def size
    @elts.size
  end

end


x = Set.new(1,2,3,4);
y = Set.new(3,4);

p x
p y

z = x - y

p z
p z.size


--
Hal Fulton


Sent via Deja.com http://www.deja.com/
Before you buy.

In This Thread

Prev Next