They can be defined like this
Struct.new(:x, :y)
But what can usefully be done with them? Specifically, how can I create an instance of such a struct? This doesn’t work
Struct.new(:x => 1, :y => 1)
(you get TypeError: can't convert Hash into String).
I’m using Ruby 1.9.2.
UPDATE:
Good pointers so far, thanks. I suppose the reason I asked this was that I have several times found myself wanting to do this
Struct.new(:x => 1, :y => 1)
just so that I can pass an object around where I can write obj.x instead of, say, instantiating a hash and having to write obj[:x]. In this case I want the structure to be really anonymous – I don’t want to pollute my namespace with anything by naming what is returned from the Struct.new call. The closest thing to that, as already suggested is
Struct.new(:x, :y).new(1, 1)
But how do you like them apples? I’m not sure I do. Is it reasonable to expect to be able to define and instantiate an anonymous struct in one go (as part of core Ruby)? I guess when I read the official Ruby docs on Struct.new I assume the word ‘anonymous’ allows this, but it doesn’t.
Struct.newreturns aClass, so you can, for example, assign it to a constant like this:or subclass it:
In both cases, you can use the resulting class like this:
If you don’t want to create a specific class (because you need to instantiate an object of that class only once), consider to use
OpenStructinstead: