15

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

4
  • 1
    When you program Ruby, you probably shouldn't try to port over your JS approaches. The languages have quite different object models, there will be a mismatch of paradigms. Commented Jul 3, 2012 at 12:02
  • That is correct, thanks for reminding. I simply need a small throw away object that's used only within a single action in my app, and perhaps the main reason is that I don't want to do it in a procedural way, it's rather clunky. :D Commented Jul 4, 2012 at 7:16
  • Then you should look at OpenStruct. Commented Jul 4, 2012 at 7:39
  • @michael Yup, I'm considering that too, it seems quite easy to add properties as in Javascript. Commented Jul 6, 2012 at 4:19

3 Answers 3

12

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer. I've seen it before, but somehow it doesn't even cross my mind, hahaha. Thanks. :)
5

You can do something like that:

foo = Object.new

def foo.bar
  1+1
end

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.