user user - 5 months ago 11
Ruby Question

Rails dynamic method name

I want to have dynamic method names like

usd_to_eur
eur_to_usd


i have
currencies = ['uah','rur','usd','eur']
and want to mix it

i try to do it with
define_method
but not sure how to do it correctly.

Answer
class MyClass
  CURRENCIES = %w|uah rur usd eur|
  CURRENCIES.permutation(2).each do |(c1, c2)|
    define_method(:"#{c1}_to_#{c2}") do
      puts "Hi, I am #{__callee__} method"
    end
  end
end

Now you have 12 methods defined. E.g.:

MyClass.new.eur_to_usd
#⇒ Hi, I am eur_to_usd method