Set ruby 2.0 keyword arguments with attr_accessor on initialize

前端 未结 2 949
一向
一向 2021-02-13 10:44

How can I dynamically set without having to write the same code all over.

Right now the code looks like this:

def initialize(keywords: keywords, title: t         


        
2条回答
  •  渐次进展
    2021-02-13 11:32

    def initialize(keywords: nil, title: nil, url: nil, adsetting: nil)
      local_variables.each do |k|
        v = eval(k.to_s)
        instance_variable_set("@#{k}", v) unless v.nil?
      end
    end
    

    or following John Ledbetter and Cary Swoveland's suggestion:

    def initialize(keywords: nil, title: nil, url: nil, adsetting: nil)
      method(__method__).parameters.each do |type, k|
        next unless type == :key
        v = eval(k.to_s)
        instance_variable_set("@#{k}", v) unless v.nil?
      end
    end
    

提交回复
热议问题