Ruby 关于类构造器的参数的扩展

yakczh · August 08, 2015 · Last by hahalq replied at August 09, 2015 · 1708 hits
class Customer
   def initialize(id, name, addr)
      @cust_id=id
      @cust_name=name
      @cust_addr=addr
   end
   def display_details()
      puts "Customer id #@cust_id"
      puts "Customer name #@cust_name"
      puts "Customer address #@cust_addr"
    end
end

cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya")

这样对属性域写死字段名,如果以后业务扩展了,要增加一个新的字段 比如 age ,就得找到相应的类把代码涉及新增加的属性全部改一遍 是不是构造函数用 Hash 传参数,扩展性更好一些呢?

如果参考 ActiveRecord,那是用 Hash 参数好。

用 Hash 的话,调用者不知道要传哪些参数吧

You need to Sign in before reply, if you don't have an account, please Sign up first.