dynamic methods


/ Published in: Other
Save to your folder(s)



Copy this code and paste it in your HTML
  1. # quick method on how to create dynamic methods or methods that share the same codebase
  2. method_names = [:dog, :cat, :man, :women]
  3.  
  4. method_names.each do |attr_name|
  5. eval <<-END
  6. def #{attr_name}
  7. class << self ; attr_reader :#{attr_name} ; end
  8. # here is where you would write what you want your methods to do
  9. # simply reference the method with an @ sign
  10. @#{attr_name} = "#{attr_name}"
  11. end
  12. END
  13. end
  14.  
  15. # the above code simply creates 4 methods named dog, cat, man, and women and outputs them as
  16. # strings
  17.  
  18.  

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.