Struct square brackets method used to instantiate?

I know that Struct class defines the [] instance method:

1.9.3p0 :014 > Struct.instance_methods(false)
=>
[:==, :eql?, :hash, :inspect, :to_s, :to_a, :values, :size, :length,
:each, :each_pair, :
[], :
[]=, :select, :values_at, :members, :pretty_print, :pretty_print_cycle,
:as_json]

This allows you to mimic hash behavior via Struct:

1.9.3p0 :016 > HashLike = Struct.new(:x,:y)
=> HashLike
1.9.3p0 :017 > h = HashLike.new(1,2)
=> #
1.9.3p0 :018 > h[:x]
=> 1
1.9.3p0 :019 > h[:y] = 100
=> 100

But I come across a use case where the square brackets method was used
as instantiation:

1.9.3p0 :001 > Point = Struct.new :x, :y do
1.9.3p0 :002 > def distance(point)
1.9.3p0 :003?> Math.sqrt((point.x - self.x) ** 2 +
1.9.3p0 :004 > (point.y - self.y) ** 2)
1.9.3p0 :005?> end
1.9.3p0 :006?> end
=> Point
1.9.3p0 :007 > Point[3,4].distance Point[0,0]
=> 5.0

That confuses me. How can [] be used both as both hash key accessors
and also instantiation (e.g. new)?

2012/10/1 John M. [email protected]

This allows you to mimic hash behavior via Struct:
But I come across a use case where the square brackets method was used
=> 5.0
For more options, visit https://groups.google.com/groups/opt_out.

That’s because the :[] method is both defined as an instance method and
as
a class method of the Point class.

Point.singleton_class.instance_methods false
=> [:new, :[], :members]


Piantanida, Ignacio Julin

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs