I am trying to make a generic method:
class Foo
attr_reader
def add(object)
item = @item.find { |item| item.(#the method is calling object.class) == object if item.is_a?(object.class)}
end
end
I want to create a generic method which compares the element of an array depending the parameter class.
Example:
item.method1 == method1 if item.is_a?(method1.class)
where method1 is the name of class.
Also, I need a complete tutorial about metaprogramming and dynamic/generic programming.
I am unsure of what you are trying to do from your example. As a general rule, in Ruby, you don’t check for types. It is dynamically typed for a reason: you can write code that works for any objects that happen to support the methods your code calls on them.
From what I can tell from your comments, you want to extend the class
Arrayso, when you call a method on an array likean_array.pack, the array is searched for an instance ofPackand returned. Ruby has a method called whenever a method is found not to exist calledModule#method_missing. For example, if I randomly decide to call4.to_dragon(magic: 4, height: 700), the Ruby interpreter will attempt to findto_dragonas a public method defined on some class or module in theFixnum(type of numbers) inheritance chain. Provided you have not done something strange to that chain, we get a call tomethod_missingon the object4with these arguments:[:to_dragon, { magic: 4, height: 700 }]. Basically, that’s the name appended to the front of the arguments, and a block should one be given.Using this technique, you can override
method_missingto get this code as a solution:You add a method to
Stringto convert a method name to a class name. Then, you redefinemethod_missingonArrayto check each element to see if the class name matches the given class name. If one is found, then that is returned. Otherwise (and we do this using Ruby’s fancy||operator), the value returned from that function isniland the second operand to||is returned. This happens to be the default implementation formethod_missing(which we get by thesuperkeyword) and returns the error the call deserves.The only potential issue with that is, if you have elements that have class names identical to method names that are already defined on arrays, then those will be called instead rather than this special technique. For example, calling
an_array.hashwill give you the hash code of the array rather than the first instance of a hash.A safer technique in this respect is more similar to what I think you were trying to do. It actually uses class objects, and you can use it to override other methods:
This defines new methods directly on an instance of an array. For example:
If this answer does not include a solution, it should at least guide you closer!