3 ms·
Ruby should have List Comprehensions like Python
I love Python's List Comprehensions, and there is just no eloquent equivalent in Ruby. We should make it happen.
- pmontra 10y agoIt's [fn(x) for x in something] vs something.map {|x| fn(x)} Coming from Ruby the Python one wasn't easy to understand. It's ok now, after a few months of writing in Python. I don't see a reason to adopt that form in Ruby or the other way around. Both forms suit well the language they belong to but won't look good in the other. Not only that, what does Python list comprehension do that Ruby can't do?
- justinzollars 10y agoI've programmed in Ruby for 6 years or so and this is my second year in Python. I think the Python function is more clear: Its obvious you will end up with an Array (List), and its iteration is more readable - "function of x for x in array"
- pmontra 10y agoIt's not the Ruby way, much like it won't be pythonic doing like Ruby does. It won't be as clear in Ruby, hence my initial difficulties with the pythonic form despite being similar to the standard mathematical notation. Ruby has methods, not functions. We call methods of Enumerable to transform list like objects (anything that includes Enumerable) and return another list like object to apply other methods to. And there is also Enumerable::Lazy for some use cases. Anyway you could open a feature request at https://bugs.ruby-lang.org/issues/ https://bugs.ruby-lang.org/issues/ and see what happens. See the two issues at https://bugs.ruby-lang.org/search?utf8=%E2%9C%93&issues=1&q=List+comprehension+ https://bugs.ruby-lang.org/search?utf8=%E2%9C%93&issues=1&q=... first