They can be defined as follows
Struct.new(:x, :y)
But what can be done profitably with them? In particular, how can I create an instance of such a structure? This does not work.
Struct.new(:x => 1, :y => 1)
(you get TypeError: can't convert Hash into String ).
I am using Ruby 1.9.2.
UPDATE:
Good pointers for now, thanks. I suppose the reason I asked about this was because I found several times that I wanted to do this.
Struct.new(:x => 1, :y => 1)
so that I can pass the object around where I can write obj.x instead of, say, creating a hash instance and writing obj[:x] . In this case, I want the structure to be truly anonymous - I do not want to pollute my namespace with anything, calling what is returned from the call to Struct.new . The closest to this, as already mentioned,
Struct.new(:x, :y).new(1, 1)
But how do you like apples? I'm not sure I know. Can one expect to be able to define and instantiate an anonymous structure at a time (as part of the core Ruby)? I think when I read the official Ruby Struct.new on Struct.new , I assume that the word “anonymous” allows it, but it doesn’t.
source share