When I was reading gem, I found a method called define_method. I wasn't sure, so I looked it up. Translated literally, it defines a method. The method named. I don't understand more and more. ..
So let's look at an example.
ruby.rb
NUMBERS = %w(zero one two three four five six seven eight nine)
NUMBERS.each_with_index do |word, num|
define_method word do |i = nil|
i ? num * i : num
end
end
p two #=> 2
p two(2) #=> 4
p nine #=> 9
p nine(3) #=> 27
** define_method is a method that can dynamically define method ** Even in the above example, the methods such as two and nine are not directly defined. It can be used as a method. This is because define_method dynamically defines two, nine methods.
ruby.rb
NUMBERS.each_with_index do |word, num|
define_method word do |i = nil|
i ? num * i : num
end
end
word is passed as an argument of define_method. This is the dynamically defined method name. Word contains the elements of the array ["zero", "one", "two", ... "nine"]. So I could use the two, nine methods.
And the block part of define_method is the processing content of the dynamically defined method.
ruby.rb
define_method word do |i = nil|
i ? num * i : num
end
As the content, if i exists, i * num is returned and If it doesn't exist, it returns num.
And i is the argument of the newly defined method. Finally, let's look at the processing result again.
p two #=> 2 #Returns num because there are no arguments
p two(2) #=> 4 #2 because there are arguments* 2 = 4
p nine #=> 9 #Returns num because there are no arguments
p nine(3) #=> 27 #9 because there are arguments* 3 = 27
This is the end of the explanation of define_method. I hope you find it useful.
** 86 days to become a full-fledged engineer **
Recommended Posts