Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 762
O.O Avatar asked Jul 03 '12 09:07

O.O


2 Answers

You can do something like that:

foo = Object.new

def foo.bar
  1+1
end
like image 150
davidrac Avatar answered Sep 28 '22 06:09

davidrac


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)
like image 37
Patrick Oscity Avatar answered Sep 28 '22 07:09

Patrick Oscity