Forum: Ruby on Rails struct square brackets method used to instantiate?

Posted by John Merlino (johnmerlino)
on 2012-10-02 03:51
(Received via mailing list)
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)
 => #<struct HashLike x=1, y=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)?
Posted by Ignacio Piantanida (Guest)
on 2012-10-02 05:10
(Received via mailing list)
2012/10/1 John Merlino <stoicism1@aol.com>

> 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
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.