Declaring instance variables iterating over a hash!

前端 未结 4 1438
忘掉有多难
忘掉有多难 2021-02-02 16:43

i want to do the following:

I want to declare the instance variables of a class iterating over a dictionary.

Let\'s assume that i have this hash

         


        
4条回答
  •  灰色年华
    2021-02-02 17:12

    class MyClass
      def initialize
        # define a hash and then
        hash.each do |k,v|
          # attr_accessor k # optional
          instance_variable_set(:"@#{k}", v)
        end
      end
    end
    

提交回复
热议问题