13

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?

3 Answers 3

19

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)
5

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.

2

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).

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.