Alle giovedì 15 novembre 2007, Wayne Magor ha scritto:
It isn't possible to define a class method (to make a constructor)
for a struct is it?
If you have:
Customer = Struct.new( "Customer", :name, :address, :zip )
joe = Customer.new( "Joe Smith", "123 Maple, Anytown NC", 12345 )
but you want it to be:
joe = ["Joe Smith", "123 Maple, Anytown NC", 12345]
Ruby will just make joe an array, right? No way around this that I
can see, is there?
You can't instruct ruby to create a class different from Array for the [x,
y, ...] construct, but you can define a method for a class, and use it to
create a new istance of the class:
class A
def initialize x, y
@x = x
@y = y
end
def A.(x, y)
new x, y
end
end
a = A[1, 2]
Since your Customer class was created using Struct.new, it already provides
this feature (at least, my trials show this, although I couldn't find
documentation about this). So, you can write:
joe = Customer["Joe Smith", "123 Maple, Anytown NC", 12345 ]
I hope this helps
Stefano