Ruby singleton classes explained

I’ve become used to JavaScript (gasp! cringe!) in writing Cartagen and sometimes find myself wanting to assign arbitrary attributes to objects I just made up. Unfortunately this JavaScript code:

var new_object = { we: 'can', make: 'up', any: 'thing' }

doesn’t work in Ruby:

new_object = {}
new_object.latitude = 'lalalala'

It yields:

undefined local variable or method `latitude' for []:Array

But you can create what are called ‘singleton objects’, as described on contextualdevelopment.com:

foobar = Array.new

def foobar.size
  "Hello World!"
end

foobar.size  # => "Hello World!"
foobar.class # => Array

Hooray!

Leave a Reply