2017-08-21 97 views
1

我想知道如何快速創建attr_accessor。是否可以這樣做:Ruby:如何快速創建attr_accessor

attr_accessor "@#{key}" 

裏面的initialize方法?

module Mymodule 
    def initialize(parameters = {}) 
    parameters.each do |key, value| 
     instance_variable_set("@#{key}", value) unless value.nil? 
    end 
    end 
end 

class Myclass 
    include Mymodule 
end 

clazz = Myclass.new attr1: "Arg1", attr2: "Arg2", attr3: "Arg3" 
    # => #<Myclass:0x43f6050 @attr1="Arg1", @attr2="Arg2", @attr3="Arg3"> 

clazz.attr1 
    # !> NoMethodError: undefined method `attr1' for #<Myclass:0x43f6050 @attr1="Arg1", @attr2="Arg2", @attr3="Arg3"> 

clazz.attr1="ATTR1" 
    # !> NoMethodError: undefined method `attr1=' for #<Myclass:0x43f6050 @attr1="Arg1", @attr2="Arg2", @attr3="Arg3"> 

回答

5

您可以通過在該實例的單例類上調用attr_accessor來定義每個實例訪問器。

class Structy 
    def initialize(parameters = {}) 
    parameters.each do |key, value| 
     singleton_class.send :attr_accessor, key 
     instance_variable_set "@#{key}", value 
    end 
    end 
end 
+0

這很有效。非常感謝你。 –

+0

@JulioCarvalho還有['Struct'](https://ruby-doc.org/core/Struct.html)和['OpenStruct'](https://ruby-doc.org/stdlib/libdoc/ ostruct/rdoc/OpenStruct.html)標準Ruby中的類。通常,這些類有助於構建結構。無論如何,在這裏你需要小心邊緣情況,例如當設置像':hash',':to_s'或':inspect'這樣的特殊鍵時,它可以隱藏你可能會隱含依賴的方法來表現它們的標準實現。允許用戶提供的參數時檢查細微的安全問題。 –