Reputation: 23169
In ruby you can go
a = { }
a['a'] = 82
a['b'] = 'foo'
puts a['a'] # 82
I wish I could use dot notation, like javascript.
puts a.a # 82
Is there a way to build object literals and access them with dot notation in ruby?
Upvotes: 13
Views: 7266
Reputation: 15010
You can create a Struct
.
A = Struct.new(:a, :b)
a = A.new(82, 'foo')
puts a.a
#=> 82
edit:
you can even do
a = { }
a['a'] = 82
a['b'] = 'foo'
Struct.new(*a.keys).new(*a.values)
Upvotes: 19
Reputation: 23586
The structure what you need is a OpenStruct
which work the same way as JS object literals. It has overwritten method_missing
method which allow adding new variables using setter methods.
Upvotes: 5
Reputation: 369536
Ruby doesn't have object literals.
Ruby is a class-based object-oriented language. Every object is an instance of a class, and classes are responsible for creating instances of themselves. You don't create objects just by writing them down, you have to ask a class to create an instance of itself by sending it a message (typically called new
, although that is only a convention).
Upvotes: 2