metaprogramming - How to create a method like ".find_by_something_and_something_else" using Ruby? -
By using Ruby I know that you can be very creative with the names of your methods, for example, Pass .find_by_this_and_that
.
How can I do this?
Example:
def get_persons_with_5_things res = [] Individuals Unit | Person If person.number_of_things ==% coincident number 5 function NAME% Res & lt; & Lt; The person end-end return ridge and
I'm also not sure how you call such things, so any signal will be appreciated.
I'm a bit confused with your example. If you define the method with the hardcoded 5 in the name of the method, then you do not need to understand magically in the body of the method. If you want to do something dynamic with the method, then something like this will happen:
def method_missing (name, * args) if name.to_s = ~ / get_persons_with _ (\ d +) _ things / Number_of_things = $ 1.to_i res = [] Individuals.Each | Person If person.number_of_things == number_of_things res & lt; & Lt; (Android) End and return super (name, * AGR) and end
[edit (Jorge W. Meteague)]: This is a more robust method of implementing the same method: /p>
def method_missing (name, * args) return super when name.to_s = ~ / get_persons_with _ (\ d +) _ things / number_ of_things = $ 1.to_i return persons Selection {| Person
-
super
passes only the original arguments without any argument, there is no need to explicitly pass them < - or
protected by an initial
back
a trailinguntil the expression does not clear the control flow
iterator, select items according to one object; However, there is already an Iterator to select items:- all < Code> Each
Select
Comments
Post a Comment