【问题标题】:Iterate Hash constants in Ruby在 Ruby 中迭代哈希常量
【发布时间】:2011-12-21 09:47:07
【问题描述】:

我有以下 Ruby 模块:

module Test
  Constant1 = {
    :key1 => :value1,
    :key2 => :value2    
  }

  Constant2 = {
    :key1 => :value1,
    :key2 => :value2    
  }
end

我正在尝试遍历声明的 Hash 常量以打印使用以下代码定义的所有键:

Test.constants.each do |constant|
  constant.keys.each do |key|
    puts "key: #{key}"
  end
end

但我得到一个NoMethodError: undefined method 'keys' for "Constant2":String,但我不知道如何将String 转换为真正的成本。有人知道怎么做吗?

【问题讨论】:

    标签: ruby hashmap constants


    【解决方案1】:

    试试这个:

    Test.constants.each do |c|
      Test.const_get(c).each do |key, value|
        puts "key: #{key}, value: #{value}"
      end
    end
    

    【讨论】:

    • .keys.each.each do |key, value|。 :-)
    • 答案也不错,抱歉我只能选择一个... +1
    【解决方案2】:

    这行得通:

    Test.constants.each do |constant|
      Test.const_get(constant).keys.each do |key|
        puts "key: #{key}"
      end
    end
    

    【讨论】:

      【解决方案3】:

      您从模块 Test 获取的常量实际上是 ["Constant1","Constant2"]。 如果你真的想以这种方式使用它,你可以将哈希值存储在模块变量中。

      【讨论】:

      • 好吧,事实是我真的不打算那样使用它:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-30
      • 2023-04-07
      • 2012-03-24
      • 2021-02-08
      • 2017-03-23
      相关资源
      最近更新 更多