How do I convert hash keys to method names?

前端 未结 5 600
暖寄归人
暖寄归人 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:53

    If the hash is inside a module, you can define methods on that module (or class) dynamically using define_method. For example:

    module Version
      module_function
    
      HASH = { 
        major: 1,
        minor: 2,
        patch: 3,
      }
    
      HASH.each do |name, value|
        define_method(name) do
          return value
        end
      end
    end
    

    This will define a Version module with major, minor, and patch methods that return 1, 2, and 3, respectively.

提交回复
热议问题