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 ]
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.
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>
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.
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
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.