Hello,
I have a exercise where I must count differences between two strings.
Now I can do
for 0 .. string1.length
But is there a better mor rubisch way to do this ?
Roelof
Hello,
I have a exercise where I must count differences between two strings.
Now I can do
for 0 .. string1.length
But is there a better mor rubisch way to do this ?
Roelof
In general I would prefer using #each over 'for', like
(0..string1.length).each {...}
If you only want to produce e.g. a single number out of a string comparison maybe #reduce/#inject would fit.
(0..string1.length).reduce(...) {...}
Regards, Paul
Am 29.05.2014 11:52, schrieb Roelof Wobben:
Hello,
I have a exercise where I must count differences between two strings.
Now I can do
for 0 .. string1.length
But is there a better mor rubisch way to do this ?
Roelof
irb:0> s="foo"
irb:0> s.chars.each {|c| p c}
"f"
"o"
"o"
=> ["f", "o", "o"]
irb:0> s.length.times {|i| p i}
0
1
2
=> 3
irb:0> s.chars.zip(t.chars)
=> [["f", "b"], ["o", "a"], ["o", "r"]]
- --
All the best, Sandor Szücs
On 29/05/14 11:52, Roelof Wobben wrote:
Hello,
I have a exercise where I must count differences between two
strings.Now I can do
for 0 .. string1.length
But is there a better mor rubisch way to do this ?
Paul Götze schreef op 29-5-2014 12:11:
In general I would prefer using #each over 'for', like
(0..string1.length).each {...}
If you only want to produce e.g. a single number out of a string comparison maybe #reduce/#inject would fit.
(0..string1.length).reduce(...) {...}
Regards, Paul
Thanks for the tip.
I will read the documentation and try to figure out how reduce can help me.
Roelof
You might consider one of the routines which computes a distance between two strings such as the following:
#===================================================
#
# LEVENSHTEIN DISTANCE
#
#==================================================
def dameraulevenshtein(seq1, seq2)
oneago = nil
thisrow = (1..seq2.size).to_a + [0]
seq1.size.times do |x|
twoago, oneago, thisrow = oneago, thisrow, [0] * seq2.size + [x + 1]
seq2.size.times do |y|
delcost = oneago[y] + 1
addcost = thisrow[y - 1] + 1
subcost = oneago[y - 1] + ((seq1 != seq2[y]) ? 1 : 0)
thisrow[y] = [delcost, addcost, subcost].min
if (x > 0 and y > 0 and seq1 == seq2[y-1] and seq1[x-1] == seq2[y] and seq1 != seq2[y])
thisrow[y] = [thisrow[y], twoago[y-2] + 1].min
end
end
end
return thisrow[seq2.size - 1]
end
I'm not the author of this. I copied it from somewhere back in June 11;
Tom Reilly
Paul Götze wrote:
In general I would prefer using #each over 'for', like
(0..string1.length).each {...}
If you only want to produce e.g. a single number out of a string comparison maybe #reduce/#inject would fit.
(0..string1.length).reduce(...) {...}
Regards, Paul
Am 29.05.2014 11:52, schrieb Roelof Wobben:
Hello,
I have a exercise where I must count differences between two strings.
Now I can do
for 0 .. string1.length
But is there a better mor rubisch way to do this ?
Roelof