Struct constructor

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 S.", "123 Maple, Anytown NC", 12345 )

but you want it to be:

 joe = ["Joe S.", "123 Maple, Anytown NC", 12345]

Ruby will just make joe an array, right? No way around this that I
can see, is there?

Alle giovedì 15 novembre 2007, Wayne M. ha scritto:

 joe = ["Joe S.", "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 S.”, “123 Maple, Anytown NC”, 12345 ]

I hope this helps

Stefano

2007/11/15, Wayne M. [email protected]:

 joe = ["Joe S.", "123 Maple, Anytown NC", 12345]

Ruby will just make joe an array, right?

Of course you cannot change the semantics of the array constructor.

No way around this that I
can see, is there?

Of course there is, this is Ruby. :slight_smile:

irb(main):001:0> Test = Struct.new :foo, :bar do
irb(main):002:1* class <<self
irb(main):003:2> alias :initialize :[]
irb(main):004:2> end
irb(main):005:1> end
=> Test
irb(main):006:0> Test[1,2]
=> #
irb(main):007:0>

Kind regards

robert

On Fri, 16 Nov 2007 01:05:44 +0900, Wayne M. [email protected]
wrote:

So how is [] defined in Ruby? Just curious. It must be a special-case.

It’s just a singleton method on the class object; “[]” is a valid method
name.

joe = Customer.send(:[], “Joe S.”, “123 Maple, Anytown NC”, 12345)

You can define a #[] method on anything.

-mental

Stefano C. wrote:

this feature (at least, my trials show this, although I couldn’t find
documentation about this). So, you can write:

joe = Customer[“Joe S.”, “123 Maple, Anytown NC”, 12345 ]

I also missed the docs for this since I was looking in the old pick-axe
book included with Ruby dists. It’s actually documented in the second
edition book on page 627. Thanks.

So how is [] defined in Ruby? Just curious. It must be a special-case.

Wayne M. wrote:

So how is [] defined in Ruby? Just curious.

obj[stuff] is syntactig sugar for obj. and
obj[stuff]=otherstuff is
syntactic sugar for obj.[]=(stuff,otherstuff). Stuff can be multiple
values
seperated by commas, otherstuff can’t.

It must be a special-case.

Not more so than <, >, <=, >=, <<, >>, ~, ^, &, +, +@, -, -@, *, ** and
so on.
Also all methods ending with a equals sign (where you can write obj.bla
= blo
instead of obj.bla=(blo)).

HTH,
Sebastian