是否有一个等效于自定义“类变量”的哈希? (红宝石)

时间:2010-01-27 03:26:07

标签: ruby scope class-variables

我使用散列哈希来在我的代码中存储设置。我想知道我的@profile哈希是否可以为类的所有实例提供相似的类变量。因此,下面的两个配置文件都有一般配置文件变量等于它们。我希望解决方案使用哈希

@profile = {
  "vB4Discussions" => {    #profile name
     "urls"  => ["vB4 General Discussions"],
     "process?" => false,
     "type" => 'Discussion'
   },
  "vB4Design".downcase => {          #profile name      
     "urls"  => ["vB4 Design and Graphics Discussions"],
     "process?" => false,
      "type" => 'Design'
   }
} 

2 个答案:

答案 0 :(得分:4)

您是否知道在找不到密钥时哈希可以调用特殊的proc?

这可以在这里使用得非常好。

require "backports"  # Needed in Ruby 1.8.6
SETTINGS = {
  "default" => {
    "urls"  => [],
    "process?" => false,
    "type" => 'Discussion'
  },
  "vB4Discussions" => {
    "urls"  => ["vB4 General Discussions"],
  },
  "vB4Design".downcase => {
    "urls"  => ["vB4 Design and Graphics Discussions"],
    "type" => 'Design'
  }
}

# Use defaults 
SETTINGS["vb4design"].default_proc = lambda{|h, k| SETTINGS["default"][k]}
SETTINGS["vB4Discussions"].default_proc = lambda{|h, k| SETTINGS["default"][k]}

# Now the defaults are used if needed:
SETTINGS["vB4Discussions"]["type"]  # ==> 'Discussion'
SETTINGS["vB4Discussions"]["process?"]  # ==> false

# Defaults can be edited later:
SETTINGS["default"]["process?"] = true
SETTINGS["vB4Discussions"]["process?"]  # ==> true
SETTINGS["vb4design"]["process?"]  # ==> true

# Specific value can be changed too
SETTINGS["vb4design"]["process?"] = false # ==> true
SETTINGS["vB4Discussions"]["process?"] # ==> true

注意:除非您有正当理由使用字符串,否则您应使用密钥符号(例如:vB4Discussions代替"vB4Discussions"

Hash.default_proc=是Ruby 1.8.7的新功能,因此您需要require "backports"才能使用它。如果您不想这样,则可以在创建哈希时指定默认proc,如下所示:

DEFAULTS = {
  "urls"  => [],
  "process?" => false,
  "type" => 'Discussion'
}

SETTINGS = {
  "default" => DEFAULTS,
  "vB4Discussions" => Hash.new{|h, k| DEFAULTS[k]}.merge!{
    "urls"  => ["vB4 General Discussions"],
  },
  "vB4Design".downcase => Hash.new{|h, k| DEFAULTS[k]}.merge!{
    "urls"  => ["vB4 Design and Graphics Discussions"],
    "type" => 'Design'
  }
}

答案 1 :(得分:2)

一种方法是对公共位使用常量,如下所示:

#!/usr/bin/ruby1.8

require 'pp'

COMMON_PROFILE = {
  "urls"  => ["vB4 General Discussions"],
  "process?" => false,
  "type" => 'Discussion'
}

@profile = {
  "vB4Discussions" => COMMON_PROFILE,
  "vB4Design".downcase => COMMON_PROFILE,
}

pp @profile

# => {"vB4Discussions"=>
# =>   {"vB4Discussions"=>
# =>     {"urls"=>["vB4 General Discussions"],
# =>      "process?"=>false,
# =>      "type"=>"Discussion"}},
# =>  "vb4design"=>
# =>   {"vB4Discussions"=>
# =>     {"urls"=>["vB4 General Discussions"],
# =>      "process?"=>false,
# =>      "type"=>"Discussion"}}}