-
-
Save jdenen/b36e0531142125df63b0eb5b50e1688f to your computer and use it in GitHub Desktop.
Comparing FP in Ruby and Python
This file contains 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
# I like true first-class functions better than either | |
# of Ruby's ways of achieving the same behavior. | |
# | |
# I'm not a big fan of having to call list on the function | |
# return here. | |
def get_from_v1(hash, f): | |
return list(f(hash)) | |
# But I really like comprehensions, which solves having to | |
# call the list function like v1. | |
def get_from_v2(hash, f): | |
return [k for k in f(hash)] | |
x = {"a": 1, "b": 2, "c": 3} | |
get_from_v1(x, dict.keys) | |
#=> ["a", "b", "c"] | |
get_from_v2(x, dict.values) | |
#=> [1, 2, 3] |
This file contains 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
# I don't like having to use the #call method | |
# on my proc object. I should just be able to pass | |
# arguments to it. It's a matter of taste, I know, | |
# but still... | |
def get_from_v1(hash, f) | |
f.call(hash) | |
end | |
# I like this even less, since I'm no longer passing | |
# around method-like objects. | |
def get_from_v2(hash, sym) | |
hash.send(sym) | |
end | |
x = { "a": 1, "b": 2, "c": 3 } | |
get_from_v1(x, ->(h){ h.keys }) | |
#=> [:a, :b, :c] | |
get_from_v2(x, :values) | |
#=> [1, 2, 3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment