簡體   English   中英

如何進一步重構ruby哈希

[英]How to further refactor a ruby hash

我正在編寫一個函數,它接受一個字符串並返回一個相應的模型類。 舊版本包含丑陋的case語句,重構版本的哈希值較低。 然而哈希仍然感覺重復我。 你能給我一些建議嗎?

# original function

def determine_node_label(category)
  label = 
    case category 
    when 'boundary box'
      Slide
    when 'circle', 'rectangle'
      GroupBox
    when 'text'
      Text
    when 'picture', 'pie', 'bar' , 'trend', 'star'
      Content
    else
      Content
    end
  return label 
end

# refactored function

def determine_node_label(category)
  label = {
    "boundary box" => Slide,
    "circle" => GroupBox,
    "rectangle" => GroupBox,
    "text" => Text,
    "picture" => Content,
    "pie" => Content,
    "bar" => Content,
    "trend" => Content,
    "star" => Content
  }
  label.default = Content
  return label["category"]
end

更新:

我會對假設label.default可能發生變化的解決方案更感興趣。 我很抱歉沒有在代碼中說清楚。

那這個呢?

LABELS = {
  "boundary box" => Slide,
  "circle"       => GroupBox,
  "rectangle"    => GroupBox,
  "text"         => Text
} 

def determine_node_label(category)
  LABELS[category] || Content
end

如果確實需要動態默認值,可以使用Hash.fetch 另外,將默認值作為方法參數傳遞。

LABELS = {
  "boundary box" => Slide,
  "circle"       => GroupBox,
  "rectangle"    => GroupBox,
  "text"         => Text
} 

def determine_node_label(category, default = 'Content')
  LABELS.fetch(category, default)
end

為了便於維護,我建議將數據保存在以下哈希中。

DATA = {
  %w| boundary\ box |              => 'Slide',
  %w| circle rectangle |           => 'GroupBox',
  %w| text |                       => 'Text',
  %w| picture pie bar trend star | => 'Content'
}
  #=> {["boundary box"]=>"Slide", ["circle", "rectangle"]=>"GroupBox",
  #    ["text"]=>"Text", ["picture", "pie", "bar", "trend", "star"]=>"Content"}

請注意,我創建了值literals(字符串)來演示如何操作此哈希。 在實際應用中,值不一定是文字。

然后提供一種從DATA和指定的默認值創建所需散列h的方法(當h沒有密鑰k時,后者由h[k]返回)。

def data_to_hash(data, default)
  data.each_with_object({}) { |(k,v),h| k.each { |obj| h[obj] = v } }.
       tap { |h| h.default = default }
end

這可以如下使用。

h = data_to_hash(DATA, 'Cat')
  #=> {"boundary box"=>"Slide", "circle"=>"GroupBox",
  #    "rectangle"=>"GroupBox", "text"=>"Text", "picture"=>"Content",
  #    "pie"=>"Content", "bar"=>"Content", "trend"=>"Content",
  #    "star"=>"Content"}
h["boundary box"]
  #=> "Slide"
h["pie"]
  #=> "Content"
h["cake"]
  #=> "Cat"

要隨后更改默認值,您可以使用修訂后的默認值再次調用data_to_hash ,或者只是執行

h.default = "Dog"

或者將后者包裝在一個方法中。

def change_default(h, new_default)
  h.default = new_default
end

change_default(h, "Dog")
  #=> "Dog"
h["pie"]
  #=> "Content"
h["cake"]
  #=> "Dog"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM