5 ms·
For me the decisive advantage Ruby has over Python is way better map/reduce/select semantics. Python's list comprehensions are just ungainly to me, and I've nev
by akanet 8y ago
For me the decisive advantage Ruby has over Python is way better map/reduce/select semantics. Python's list comprehensions are just ungainly to me, and I've never understood the reverence for them.
- maksimum 8y agoI think one reason people like comprehensions in python is because they provide an intuitive syntax for both map and select/filter. As I understand it, reduce still provides functionality that you can't get from comprehensions alone. I feel like comprehensions are expressive and readable unless you try to do multiple maps in the same comprehension. I looked up the select/filter syntax in ruby. I guess the main difference is that the name of the element you're iterating over is left implicit compared to comprehensions, but equivalent to filter. details.select{ |item| item[:qty] != "" } [item for item in details if item.qty != ''] filter(lambda item: item.qty != '', items) I'm curious if the implicitness is cumbersome when you need to do a selection that combines multiple lists. How would you express the third line of the following in ruby? A = range(65,69) B = ['A', 'B', 'C', 'D'] [a for a, b in zip(A, B) if b=='C']
- onli 8y agoMy approach would probably be to create the zipped list in the beginning, split it for the comparison and then select the wanted element: A = (65..69).to_a B = ['A', 'B', 'C', 'D'] A.zip(B).select{|x, y| y == 'C' }.map{|x, y| x }
- maksimum 8y agoThanks! That looks equivalent to python without comprehensions. As far as I can tell the difference in the expressiveness of `map/filter/reduce` is mainly about whether you like or don't like comprehensions. Do you have any examples where you believe ruby has cleaner syntax?
- dragonwriter 8y ago> As far as I can tell the difference in the expressiveness of `map/filter/reduce` is mainly about whether you like or don't like comprehensions. Comprehensions don't replace reduce, they are equivalent to a combination of map, filter, and flat_map. The difference is not just about comprehensions, since map/filter/reduce, and friends, in Python are functions, where in Ruby they are methods; so in Python when you can't do it all with comprehensions (reduce, zip, etc.), it's either imperative loops or functional notation (inside-out), while Ruby uses method call notation, which results in operations reading in the order of application.
- maksimum 8y agoGreat clarification. You're right, reduce was a typo. I definitely like how method call notations can be read left-to-right rather than inside out. Now I'm curious why python developers decided not to add these 'transformation methods' to all Iterables.