2011-03-19 42 views
1

嘿傢伙, 我有5個模型屬性,例如'str'和'dex'。用戶有力量,敏捷屬性。將字符串映射到Ruby Rails中的另一個字符串

當我調用user.increase_attr('dex')時,我想通過'dex'來完成,而不必一直傳遞'dexterity'字符串。

當然,當我需要做user.dexterity + = 1然後保存它時,我可以檢查是否能力=='dex'並將它轉換爲'靈巧'。

但是,做一個好的紅寶石方法是什麼?

回答

1
def increase_attr(attr) 
    attr_map = {'dex' => :dexterity, 'str' => :strength} 
    increment!(attr_map[attr]) if attr_map.include?(attr) 
end 

基本上創建一個Hash,其中包含'dex','str'等關鍵字並指向該單詞的擴展版本(以符號格式)。

+0

謝謝你的回答。這是非常接近的,但我似乎無法增加價值。我試着像上面那樣增加。我需要增加屬性的'強度'和'strength_points'。我試過類似「self.increment!((ability <<'_points')。to_sym)」where'=='strength',但它不起作用:/ – Spyros 2011-03-19 01:41:38

+0

也許我可以使用save和eval?我將不得不測試一下。 – Spyros 2011-03-19 01:42:56

+0

嗯,它幾乎工作,thanx :) – Spyros 2011-03-19 01:47:50

3

看看Ruby的Abbrev模塊,它是標準庫的一部分。這應該給你一些想法。

require 'abbrev' 
require 'pp' 

class User 
    def increase_attr(s) 
    "increasing using '#{s}'" 
    end 
end 

abbreviations = Hash[*Abbrev::abbrev(%w[dexterity strength speed height weight]).flatten] 

user = User.new 
user.increase_attr(abbreviations['dex']) # => "increasing using 'dexterity'" 
user.increase_attr(abbreviations['s']) # => "increasing using ''" 
user.increase_attr(abbreviations['st']) # => "increasing using 'strength'" 
user.increase_attr(abbreviations['sp']) # => "increasing using 'speed'" 

如果傳遞了一個不明確的值(「s」),則不匹配。如果在散列中找到唯一值,則返回的值是完整字符串,這使得將短字符串映射到完整字符串變得很容易。

因爲具有不同長度的觸發字符串會讓用戶感到困惑,所以您可以將所有散列元素的鍵比最短的明確鍵更短。換句話說,由於「速度」(「sp」)和「強度」(「st」)的衝突,意味着「h」,「d」和「w」需要去除,所以刪除短於兩個字符的任何字符。這是一個「善待貧窮的用戶」的東西。

下面是當Abbrev::abbrev發揮它的魔力並被強制進入散列時創建的東西。

pp abbreviations 
# >> {"dexterit"=>"dexterity", 
# >> "dexteri"=>"dexterity", 
# >> "dexter"=>"dexterity", 
# >> "dexte"=>"dexterity", 
# >> "dext"=>"dexterity", 
# >> "dex"=>"dexterity", 
# >> "de"=>"dexterity", 
# >> "d"=>"dexterity", 
# >> "strengt"=>"strength", 
# >> "streng"=>"strength", 
# >> "stren"=>"strength", 
# >> "stre"=>"strength", 
# >> "str"=>"strength", 
# >> "st"=>"strength", 
# >> "spee"=>"speed", 
# >> "spe"=>"speed", 
# >> "sp"=>"speed", 
# >> "heigh"=>"height", 
# >> "heig"=>"height", 
# >> "hei"=>"height", 
# >> "he"=>"height", 
# >> "h"=>"height", 
# >> "weigh"=>"weight", 
# >> "weig"=>"weight", 
# >> "wei"=>"weight", 
# >> "we"=>"weight", 
# >> "w"=>"weight", 
# >> "dexterity"=>"dexterity", 
# >> "strength"=>"strength", 
# >> "speed"=>"speed", 
# >> "height"=>"height", 
# >> "weight"=>"weight"} 
相關問題