Skip to content

Instantly share code, notes, and snippets.

@gilesbowkett
Created December 5, 2010 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gilesbowkett/729329 to your computer and use it in GitHub Desktop.
Save gilesbowkett/729329 to your computer and use it in GitHub Desktop.
I have no idea what this field is for
# my first serious ruby question in like forever:
class Array
def token_diff(other)
memo = 0
self.each_with_index do |element, index|
memo += 1 if other[index] != element
end
return memo
end
end
# this works only for the naïvest of cases:
# >> [:a, :b, :c].token_diff([:a, :b, :c])
# => 0
# >> [:a, :b, :c].token_diff([:a, :b])
# => 1
# >> [:a, :b, :c].token_diff([:a])
# => 2
# and fails...
# >> [:a, :b].token_diff([:a, :b, :c])
# => 0
# I know there are better, more elegant ways to do this, but I'm stumped. halp!!!1
@judofyr
Copy link

judofyr commented Dec 5, 2010

What about something like this?

class Array
  def token_diff(other)
    if size > other.size
      base = self
    else
      base, other = other, self
    end

    base.zip(other).count { |a, b| a != b }
  end
end

@gilesbowkett
Copy link
Author

I'll try that.

just in case, real specs:

token_diff([:a, [[:b, [:c, "d"], [:c, "e"]], [:f, "g"]]], [:a, [[:b, [:c, "d"], [:c, "e"]], [:f, "g"]]]).should == 0
token_diff([:a, [[:b, [:c, "d"], [:c, "e"]], [:f, "g"]]], [:a, [[:b, [:c, "d"], [:c, "e"]], [:f, "h"]]]).should == 1

@gilesbowkett
Copy link
Author

I get a no method error for count. Is that 1.9? I'm using 1.8.

there's an implementation here http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/75193

@gilesbowkett
Copy link
Author

and also:

a = [:a, [[:b, [:c, "d"], [:c, "e"]], [:f, "g"]]]
b = [:a, [[:c, "h"], [:a, [[:b, [:c, "d"], [:c, "e"]], [:f, "g"]]]]]
token_diff(a, b).should == 1

a = [:a, [[:b, [:c, "d"], [:c, "e"]], [:f, "g"]]]
b = [:a, [[:c, "h"], [:a, [[:b, [:c, "d"], [:c, "e"]], [:f, "i"]]]]]
token_diff(a, b).should == 2

@dhinojosa
Copy link

if (list1.size > list2.size) (list1 - (list1 & list2)).size else list2 - (list2 & list1).size() end

Try that one too.

@Vaguery
Copy link

Vaguery commented Dec 5, 2010

I don't understand

a = [:a, [[:b, [:c, "d"], [:c, "e"]], [:f, "g"]]]
b = [:a, [[:c, "h"], [:a, [[:b, [:c, "d"], [:c, "e"]], [:f, "i"]]]]]
token_diff(a, b).should == 2

Both a and b have 2 elements; the first element of each is :a.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment