Skip to content

Instantly share code, notes, and snippets.

@mudge
Last active August 29, 2015 14:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mudge/60f08e5cdae535b1155f to your computer and use it in GitHub Desktop.
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
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]
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