Is there a Ruby equivalent to PHP's extract?

后端 未结 2 1022
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-18 06:35

I can create a block that will extract hash elements and turn them into local variables, but I\'m wondering if a native method already exists. Something like this:



        
2条回答
  •  半阙折子戏
    2021-01-18 06:57

    You can get close:

    bar, bar2 = h.values_at :foo, :foo2
    

    Or I suppose we could extend Hash to extract into instance variables:

    class Hash
      def extract o
        each { |k, v| o.instance_variable_set '@' + k.to_s, v }
      end
    end
    
    h.extract self
    
    p [@foo, @foo2]
    

提交回复
热议问题