O.O
O.O

Reputation: 7287

How to create object and it's methods dynamically in Ruby as in Javascript?

I recently found that dynamically creating object and methods in Ruby is quite a work, this might be because of my background experience in Javascript.

In Javascript you can dynamically create object and it's methods as follow:

function somewhere_inside_my_code() {
  foo = {};
  foo.bar = function() { /** do something **/ };
};

How is the equivalent of accomplishing the above statements in Ruby (as simple as in Javascript)?

Upvotes: 15

Views: 6595

Answers (3)

Patrick Oscity
Patrick Oscity

Reputation: 54684

You can achieve this with singleton methods. Note that you can do this with all objects, for example:

str = "I like cookies!"

def str.piratize
  self + " Arrrr!"
end

puts str.piratize

which will output:

I like cookies! Arrrr!

These methods are really only defined on this single object (hence the name), so this code (executed after the above code):

str2 = "Cookies are great!"
puts str2.piratize

just throws an exception:

undefined method `piratize' for "Cookies are great!":String (NoMethodError)

Upvotes: 12

Victor Moroz
Victor Moroz

Reputation: 9225

You can try OpenStruct: http://www.ruby-doc.org/stdlib-1.9.3/libdoc/ostruct/rdoc/OpenStruct.html, it resembles JavaScript in some way, but only with properties, not methods. Ruby and JavaScript use too different ideas for objects.

Upvotes: 3

davidrac
davidrac

Reputation: 10738

You can do something like that:

foo = Object.new

def foo.bar
  1+1
end

Upvotes: 5

Related Questions