user3314570 user3314570 - 5 months ago 14
Ruby Question

Define many similar methods in one place

I've seen things like

[:toto, :tata, :titi].each do |kind|
if "create_#{kind}" do
something
end
end


with the methods
create_toto
,
create_tata
and
create_titi
existing in another file. I was wondering if it's maybe possible to do it with the definition of method?

I have multiple methods named
end_{something}
which do the samed exact thing and I would like to know if it's possible to group them into one and only, with the same mechanism as above.

Answer

Take notice the expression if "create_#{kind}" will always return true, you probably mean defined?("create_#{kind}") which checks if a method is defined.

you can use the 'method_missing' method:

def method_missing(method_name, *arguments, &block)
  method = method_name.to_s 

  case method
  when 'create_toto'
    #do somthing
  when 'create_tata'
    #do somthing
  when 'create_titi'
    #do somthing
  else
    super
  end
end

You can also define methods dynamically:

[:toto, :tata, :titi].each do |kind|
  define_method "create_#{kind}" do
    #do something
  end
end
Comments