Reputation: 53
When getting user input, is there a way to recognise "gr*y"
(where the *
character doesn't matter) other than writing each spelling like "grey"
and "gray"
in my code?
Upvotes: 1
Views: 159
Reputation: 15045
The term you're looking for is called fuzzy match
or fuzzy search
.
I've found 3 libraries, which provide such a functionality:
You can look through the docs of each of them and decide, which is more preferable for you case. I just show the example of amatch
:
require 'amatch'
include Amatch
m = Levenshtein.new("grey")
m.match('gray') # 1
m.match('pray') # 2
It calculates the Levenshtein distance between two words: the minimum number of single-character edits (insertions, deletions or substitutions) required to change one word into the other. Thus, in order to count gray
and grey
words as the same, you need to set allowable distance as 1
.
Upvotes: 2
Reputation: 10359
This can be achieved using a regular expression. Though, you probably wouldn't want to match any character -- it might work in this particular instance, but could completely change the meaning of other words.
For example, /gr(a|e)y/
would match both "gray" and "grey".
If you did want to match any single character, you could use a range, like /gr[a-zA-Z]y/
.
Here's a working example on Rubular.
There's also probably a gem which wraps up all of these common spellings. I'd suggest searching on rubygems.org and ruby-toolbox.com.
Upvotes: 1