-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I took actually ruby as an example:
array.delete_if{|item| item>1}