How to Do Advanced String Comparison in Ruby

How to do advanced string comparison in Ruby?

You may want to try the Levenshtein string distance algorithm for this. http://rubygems.org/gems/text has an implementation of this along with other helpful string comparison utils.

How do I do String comparison in Ruby?

The string returned by gets will have a linebreak at the end. Use String#chomp to remove it (i.e. state_abbreviation = gets.chomp).

PS: Your code would look much cleaner (IMHO) if you used case-when instead of if-elsif-elsif.

How to compare a string against multiple other strings

["string1","string2","string3"].include? myString

Ruby compare two strings similarity percentage

I think your question could do with some clarifications, but here's something quick and dirty (calculating as percentage of the longer string as per your clarification above):

def string_difference_percent(a, b)
longer = [a.size, b.size].max
same = a.each_char.zip(b.each_char).count { |a,b| a == b }
(longer - same) / a.size.to_f
end

I'm still not sure how much sense this percent difference you are looking for makes, but this should get you started at least.

It's a bit like Levensthein distance, in that it compares the strings character by character. So if two names differ only by the middle name, they'll actually be very different.

What methods gets called when I try to compare custom object with string?

You need to override your class' == method.

class MyClass
def ==(other)
# custom equal comparison logic here
# if you just need string comparison
to_s == other
end
end

Ruby: matching a string against another object that may be a string or regexp

This is a shortened version of your approach:

def compare(str, thelist)
thelist.any? { |item| item.match(str) }
end

ruby random string comparison method

Your problem is: Every time you call type it returns a random value. Therefore you check against different values in each if condition.

Change your code to this:

def self.deadline
case type
when "Early"
puts "early"
# removed other code
when "Late"
puts "late"
#removed other code
when "On Time"
puts "on time"
#removed other code
else
puts "Missing"
end
end


Related Topics



Leave a reply



Submit