How do I convert hash keys to method names?

前端 未结 5 599
暖寄归人
暖寄归人 2020-12-02 14:37

This is my hash:

tempData = {\"a\" => 100, \"here\" => 200, \"c\" => \"hello\"}

I need to access the hash keys as a method like:

5条回答
  •  醉话见心
    2020-12-02 14:43

    you can extend the Hash class in the following way.

    class Hash
          # return nil whenever the key doesn't exist
          def method_missing(m, *opts)
            if self.has_key?(m.to_s)
              return self[m.to_s]
            elsif self.has_key?(m.to_sym)
              return self[m.to_sym]
            end
            return nil
    
            # comment out above line and replace with line below if you want to return an error
            # super
          end
    end
    

提交回复
热议问题