I would like to do the following in Ruby:   Create a class with a method in it 1.5 Create an instance of the class Create a reference to the method in the instance Execute the method later   Something like this:  class Cat   def meow     puts "meow"   end end  my_cat = Cat.new portable_meow = my_cat.method("meow") portable_meow.execute # outputs "meow"
120580
Is it possible in Ruby to get a reference to methods of an object ( I would like to know if this can be done without procs/lambdas ) , for example , consider the following code :   class X   def initialize     @map = {}     setup_map   end    private   def setup_map     # @map["a"] = get reference to a method     # @map["b"] = get reference to b method     # @map["c"] = get referebce to c method   end    public   def call(a)     @map["a"](a) if a > 10     @map["b"](a) if a > 20     @map["c"](a) if a > 30   end    def a(arg)      puts "a was called with #{arg}"   end    def b(arg)      puts "b was called with #{arg}"   end    def c(arg)     puts "c was called with #{arg}"   end end   Is it possible to do such thing ? I would like to avoid procs/lambdas because I want to be able to change the behaviour of A,B,C by subclassing .
46642
Let's say I have a class that has a member called data which is a list.    I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.  What's your technique for doing this?  Do you just check the type by looking at __class__?  Is there some trick I might be missing?  I'm used to C++ where overloading by argument type is easy.
24042
To make a JavaScript class with a public method I'd do something like:  function Restaurant() {}  Restaurant.prototype.buy_food = function(){    // something here }  Restaurant.prototype.use_restroom = function(){    // something here }   That way users of my class can:  var restaurant = new Restaurant(); restaurant.buy_food(); restaurant.use_restroom();   How do I create a private method that can be called by the buy_food and use_restroom methods but not externally by users of the class?  In other words, I want my method implementation to be able to do:  Restaurant.prototype.use_restroom = function() {    this.private_stuff(); }   But this shouldn't work:  var r = new Restaurant(); r.private_stuff();   How do I define private_stuff as a private method so both of these hold true?  I've read  a few times but it doesn't seem like "private" methods can be called by public methods and "privileged" methods can be called externally.
37713
I am trying to create a MATLAB class with a member variable that's being updated as a result of a method invocation, but when I try to change the property within the class it (apperently, from what I understood from MATLAB's memory management) creates a copy of the object and then modifies it, leaving the original object's property untouched.  classdef testprop       properties           numRequests=0;       end       methods           function Request(this, val)               disp(val);               this.numRequests=this.numRequests+1;           end       end   end     .  &gt;&gt; a=testprop; &gt;&gt; a.Request(9); &gt;&gt; a.Request(5);   &gt;&gt; a.numRequests    ans = 0
123261
Is there any way to redefine a class or some of its methods without using typical inheritance? For example: class third_party_library {     function buggy_function() {         return 'bad result';     }     function other_functions(){         return 'blah';     } }  What can I do to replace buggy_function()? Obviously this is what I would like to do class third_party_library redefines third_party_library{     function buggy_function() {         return 'good result';     }     function other_functions(){         return 'blah';     } }  This is my exact dilemma: I updated a third party library that breaks my code. I don't want to modify the library directly, as future updates could break the code again. I'm looking for a seamless way to replace the class method. I've found this  that says it can do it, but I'm wary as it's 4 years old. EDIT: I should have clarified that I cannot rename the class from third_party_library to magical_third_party_library or anything else because of framework limitations. For my purposes, would it be possible to just add a function to the class? I think you can do this in C# with something called a &quot;partial class.&quot;
111415
I have a Generic class like that :  public class Repository&lt;T&gt; {...}   And I need to instance that with a string ... Example :  string _sample = "TypeRepository"; var _rep = new Repository&lt;sample&gt;();   How can I do that? Is that even possible?  Thanks!
22006
When defining a method on a class in Python, it looks something like this:  class MyClass(object):     def __init__(self, x, y):         self.x = x         self.y = y   But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype.    Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument?
79010
Take the following class as an example:  class Sometype {     int someValue;      public Sometype(int someValue)     {         this.someValue = someValue;     } }   I then want to create an instance of this type using reflection:  Type t = typeof(Sometype); object o = Activator.CreateInstance(t);   Normally this will work, however because SomeType has not defined a parameterless constructor, the call to Activator.CreateInstance will throw an exception of type MissingMethodException with the message "No parameterless constructor defined for this object." Is there an alternative way to still create an instance of this type? It'd be kinda sucky to add parameterless constructors to all my classes.
81218
I am trying to do a new environment or command (i tried both) where i can put in the name, description and code of a Method in c++ and it gives me a new section with the MethodName, the code listed and the description below. But i am not able to use the listings environment in a new command or new environment.. Consider my MWE   \documentclass[a4paper,11pt]{article} \usepackage{listings}  \newcommand{\method}[3] { \section{#1}\label{#1} \begin{lstlisting} #2 \end{lstlisting} #3 }   \begin{document}  \method{MethodName}{Method Void MethodName()}{Description of the Method blablabla}  \end{document}   How can I fix this?   I would prefer to do it using a macro since I don't need an ending.
5309
How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived?  Was thinking maybe  might have helped me out here, but it doesn't seem to give me what I want. And short of parsing the __class__ member, I'm not sure how to get at this information.
22496
I have some controller methods I'd like to share. What is the best practice for doing this in ruby on rails? Should I create an abstract class that my controllers extend, or should I create module and add it in to each controller? Below are the controller methods I want to share:  def driving_directions   @address_to = params[:address_to]   @address_from = params[:address_from]   @map_center = params[:map_center_start]    # if we were not given a center point to start our map on   # let's create one.   if !@map_center &amp;&amp; @address_to     @map_center = GeoKit::Geocoders::MultiGeocoder.geocode(@address_to).ll   elsif !@map_center &amp;&amp; @address_from     @map_center = GeoKit::Geocoders::MultiGeocoder.geocode(@address_from).ll   end end  def printer_friendly   starting_point = params[:starting_point].split(',').collect{|e|e.to_f}   ne = params[:ne].split(',').collect{|e|e.to_f}   sw = params[:sw].split(',').collect{|e|e.to_f}   size = params[:size].split(',').collect{|e|e.to_f}   address = params[:address]    @markers = retrieve_points(ne,sw,size,false)   @map = initialize_map([[sw[0],sw[1]],[ne[0],ne[1]]],[starting_point[0],starting_point[1]],false,@markers,true)   @address_string = address end
83470
Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code:  class hi:   def __init__(self):     self.ii = "foo"     self.kk = "bar"   Is there a way for me to do this:  &gt;&gt;&gt; mystery_method(hi) ["ii", "kk"]   Edit: I originally had asked for class variables erroneously.
7247
Ruby can add methods to the Number class and other core types to get effects like this:  1.should_equal(1)   But it seems like Python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that type can't be modified?  Update: Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in Python, would allow this.  To answer some of you: The reason I might want to do this is simply aesthetics/readability.    item.price.should_equal(19.99)   This reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:  should_equal(item.price, 19.99)   This concept is what  and some other Ruby frameworks are based on.
114087
Say I've got a class like this:  class Test {   int x;   SomeClass s; }   And I instantiate it like this:  Test* t = new Test;   Is x on the stack, or the heap? What about s?
80444
$0 is the variable for the top level Ruby program, but is there one for the current method?
97585
Is it possible to call a method by reflection from a class?  class MyObject {     ...   //some methods      public void fce() {         //call another method of this object via reflection?     } }   Thank you.
37849
I'm working on a project in C#. The previous programmer didn't know object oriented programming, so most of the code is in huge files (we're talking around 4-5000 lines) spread over tens and sometimes hundreds of methods, but only one class. Refactoring such a project is a huge undertaking, and so I've semi-learned to live with it for now.  Whenever a method is used in one of the code files, the class is instantiated and then the method is called on the object instance.  I'm wondering whether there are any noticeable performance penalties in doing it this way? Should I make all the methods static "for now" and, most importantly, will the application benefit from it in any way?