Last active
August 29, 2015 14:10
-
-
Save mudge/60f08e5cdae535b1155f to your computer and use it in GitHub Desktop.
Copying Clojure's IFn interface for Set#to_proc and Hash#to_proc. More details at http://mudge.name/2014/11/26/data-structures-as-functions.html
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
class Hash | |
def to_proc | |
method(:[]).to_proc | |
end | |
end | |
%w(a b c d).map(&{"a" => 1, "b" => 2, "c" => 3}) | |
# => [1, 2, 3, nil] | |
# Or, a more readable example: | |
person = { name: "Robert Paulson", age: 43 } | |
name, age = %i(name age).map(&person) | |
# => ["Robert Paulson", 43] |
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
class Set | |
def to_proc | |
method(:include?).to_proc | |
end | |
end | |
(1..10).select(&Set[1, 5, 7]) | |
# => [1, 5, 7] | |
# Or to be closer to Clojure's behaviour... | |
class Set | |
def to_proc | |
->(x) { x if include?(x) } | |
end | |
end | |
# A more readable example: | |
acceptable_values = Set[2, 4, 6, 8] | |
user_submission = [1, 3, 4, 5, 7, 8] | |
user_submission.select(&acceptable_values) | |
# => [4, 8] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment