Skip to content

Instantly share code, notes, and snippets.

@jblanche
Forked from devboy/typeParams.as
Created November 22, 2011 23:45
Show Gist options
  • Save jblanche/1387448 to your computer and use it in GitHub Desktop.
Save jblanche/1387448 to your computer and use it in GitHub Desktop.
This is not a language flamewar, Haxe really do looks great and one should use the language he feels the more comfortable with. But I wanted to show how Ruby Duck Typing can handle this kind of situations.
# Ruby is using Duck Typing, rather than checking types, Ruby checks if an object can or cannot respond to a method.
# Here is a "port" of the Haxe example in Ruby.
# Ruby is not a compiled language, so that the "easiest" syntax comes with some shortcoming,
# those errors can only be detected at runtime, your favorite IDE won't warn you before :)
ints = [1, 2, 3]
strings = ["a", "bb", "ccc"]
def biggerThan1(x)
x > 1
end
def longerThan1(x)
x.length > 1
end
def array_delete_if(array, method)
array.delete_if{|i| send(method, i)}
end
array_delete_if(ints, :biggerThan1) # [ 1 ]
array_delete_if(strings, :longerThan1) # [ "a" ]
array_delete_if(strings, :biggerThan1) # Comparison of String with 1 failed (ArgumentError)
array_delete_if(ints, :longerThan1) # undefined method `length' for 1:Fixnum
@devboy
Copy link

devboy commented Nov 23, 2011

I took actually ruby as an example:
array.delete_if{|item| item>1}

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