Skip to content

Instantly share code, notes, and snippets.

@jdenen
Created February 9, 2018 03:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdenen/b36e0531142125df63b0eb5b50e1688f to your computer and use it in GitHub Desktop.
Save jdenen/b36e0531142125df63b0eb5b50e1688f to your computer and use it in GitHub Desktop.
Comparing FP in Ruby and Python
# 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]
# 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