2011-03-19 84 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"} 
相关问题