Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - create methods with a dynamic names in a loop

Maybe it's not wise question... but I have a one.
I was playing with Ruby and tried to create methods with a dynamic names in a loop, like this:

class Test

    .....
    class methods 
    .....

    for i in 1..100
       def method_#{i}
          my_hash[:test].first[i]
       end
    end
end

I noticed that's impossible, so... Is there any solution using a :define_method, or :send to solve my problem and gets methods like: method_0, method_1, method_2 etc. which return my_hash[:test].first[1], my_hash[:test].first[2] etc. ?

like image 395
Neologis Avatar asked Jan 09 '23 11:01

Neologis


1 Answers

You can do it using define_method. Here is the code:

class Test
    .....
    class methods 
    .....

    1.upto(100) do |num|
        define_method("method_#{num}") do
            my_hash[:test].first[num]
        end
    end
end
like image 195
Noman Ur Rehman Avatar answered Jan 18 '23 17:01

Noman Ur Rehman