优化类中的构造函数

时间:2018-03-20 14:39:48

标签: ruby

如何使用哈希,我可以更好地编写这个类吗?

class Bank
    def initialize(name, city, country, max_credit_value, min_credit_value, credit_time)
        @name = name
        @coordinates = coordBainates
        @country = country
        @max_credit_value = max_credit_value
        @min_credit_value = min_credit_value
        @interest_rate = interest_rate
        @credit_time = credit_time 
    end
end

也许有更好的方法?

2 个答案:

答案 0 :(得分:2)

您可以在数组中定义参数,这样就不必保持所有内容同步。使用一点元编程将它们转换为实例变量:

class Bank
  def initialize opts={}
    keys = %i{name coordinates country max_credit_value min_credit_value interest_rate credit_time}
    raise ArgumentError, "invalid options: expected #{keys}, got #{opts.keys}" unless keys.sort == opts.keys.sort
    keys.each { |key| instance_variable_set "@#{key}", opts[key] }
  end
end

然后用

初始化
Bank.new name: "Foobar", coordinates: [2, 5], country: "US", etc...

答案 1 :(得分:1)

如果你的目标是最短的代码,而你的构造函数代码只有分配,那么这可能是更好

class Bank < Struct.new(:name, :city, :country, :max_credit_value, :min_credit_value, :credit_time)
end