by sedeki · 5y ago · 0 comments
I'm pretty sure it does and that it is full-fledged, compared to Python's intentionally restricted `lambda` syntax.
What you do have in Ruby is Proc, that can be used kind of like first class functions, so you don't really miss out on much.
See:
* https://ruby-doc.org/core-2.7.1/Method.html
* https://ruby-doc.org/core-2.7.1/Object.html#method-i-method
$ irb
2.3.3 :001 > p = Kernel.method(:puts)
=> #<Method: Kernel.puts>
2.3.3 :002 > p.call "Hello"
Hello
=> nil
2.3.3 :003 > def run_a_method(meth, *args)
2.3.3 :004?> meth.call(*args)
2.3.3 :005?> end
=> :run_a_method
2.3.3 :006 > run_a_method(p, "Hi!")
Hi!
=> nil
2.3.3 :007 >
ps. this also works with the "to_proc" operator (&) so you can do this: [1, 2, 3].each(&Kernel.method(:puts))
(but I wouldn't necessarily recommend this since it's not very readable, at least to my eyes).As far as defining anonymous functions, literally all you have to do is:
my_func = -> (input) { output }
That makes a “lambda” which is literally just a function you can pass around anonymously.
You call it via either my_func.call(input) or simply my_func[input].
That capability is used all over the place.
Ruby absolutely has first class functions, the only thing you can say is it the syntax is slightly different if you want to use them anonymously (with no object context).
Ruby's Method class matches the design "everything is an object" (strings, numbers, modules & classes themselves...). Are regular expressions first class in ruby? There is top-level syntactic sugar for REs (/.../) but REs are just instances of `Regexp`. It's just syntax. I don't think you can argue Python REs are first class: I have to drag in `re` and then `re.compile()` a string (and my editor won't know to syntax highlight metachars or interpolation). I use REs more often than method references in either language...
But I'm not trying to "whataboutwhataboutwhatabout" here. I'm trying to say there's a difference of philosophy. Ruby Methods are just more objects (Method<Object). They aren't some sort of blessed type, just like everything else. Everything descends from Object. Kernel is just a module. Method is just a class. And so on. In that context, what does it mean to be "first class"? Objects are first class and methods are objects. QED. No?
(FWIW I agree on ruby's optional parens, too much inconsistency for a few less lit pixels on the screen).
You can do the exact same thing with object methods if you want, eg. my_puts = Kernel.method(:puts).
You can even do this in one line and stop the auto parenthesis behavior if you want.
foo = method def foo ... end
Now foo will reference the method and you have to use foo() to call it.
The reason that people don’t do a bunch of that in Ruby is that the support for anonymous blocks is so convenient That there aren’t that many cases where you really need anonymous functions detached from any object.
(Please see my sibling comment for example).