Let's say that I have the following methodsdef name(value)    if value        attribute['name'] = value    end    return attribute['name']enddef surname(value)    if value        attribute['surname'] = value    end    return attribute['surname']enddef age(value)    if value        attribute['age'] = value    end    return attribute['age']enddef gender(value)    if value        attribute['gender'] = value    end    return attribute['gender']endAs you see the structure is incredible similar. Im just defining getters and setters.How could this be done in a more DRY manner?
Ruby - Methods with same structure in a DRY manner
ruby
In order to define accessors dynamically, I would use methods like #attribute_name for the getter and #attribute_name=(value) to be able to set values to nil or false (which your code prevents). Plus your API won't be confusing to other rubyists (typing foo_instance.name(nil) in order to get a value isn't really the Ruby Way).class Foo  attr_accessor :foo, :bar, :bazendNow, if you need to do something else entirely and define multiple methods with the same body, I would recommend using Class#define_methodclass Foo  def initialize(attributes = {})    @attributes = attributes  end  %w(foo bar baz).each do |name|    define_method name do      @attributes[name] # consider using Hash#fetch here    end    define_method #{name}= do |value|      @attributes[name] = value    end  endendFor the sake of completeness, here's my answer without changing anything to the original code behavior :%w(name surname age gender).each do |attribute_name|  define_method attribute_name do |value|    attribute[attribute_name] = value if value    attribute[attribute_name]  endend