Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby object literals (ala javascript)

Tags:

ruby

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?

like image 691
tester Avatar asked Sep 28 '12 01:09

tester


People also ask

What is object and object literal in JavaScript?

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 = {

What is an object literal Ruby?

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.

What is an object literal JavaScript example?

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)

What is object literal in ES6?

Object Property Initializer Before ES6, the object literal is a collection of name-value pairs. For example, In ES5. function user(name, division) { return {


2 Answers

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)
like image 163
oldergod Avatar answered Oct 12 '22 11:10

oldergod


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.

like image 24
Hauleth Avatar answered Oct 12 '22 11:10

Hauleth