Посмотрите на модуль 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"}