tester
tester

Reputation: 23169

Ruby object literals (ala javascript)

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

Answers (3)

oldergod
oldergod

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

Hauleth
Hauleth

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

Jörg W Mittag
Jörg W Mittag

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

Related Questions