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)? -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk@googlegroups.com. To unsubscribe from this group, send email to rubyonrails-talk+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/groups/opt_out.