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?
In plain English, an object literal is a comma-separated list of name-value pairs inside of curly braces. Those values can be properties and functions. Here's a snippet of an object literal with one property and one function. var greeting = {
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.
Object property initializer shorthand Prior to ES6, an object literal is a collection of name-value pairs. For example: function createMachine(name, status) { return { name: name, status: status }; } Code language: JavaScript (javascript)
Object Property Initializer Before ES6, the object literal is a collection of name-value pairs. For example, In ES5. function user(name, division) { return {
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With