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. ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With