4 ms·
> Ruby keeps going with its methods-first approach, except instead of each we have a new set of methods commonly implemented on collections, as below Once you
by danielheath 2y ago
> Ruby keeps going with its methods-first approach, except instead of each we have a new set of methods commonly implemented on collections, as below
Once you implement `each`, `include Enumerable` is all it takes to get the full set of collection methods (including `max`/`min` etc, if the entries define `<=>`).
- vidarh 2y agoIndeed. The entire article largely read like "Python developer learns Ruby", and on top of that now fairly dated Ruby, though I'll make some concessions for him wanting to show a close parallel to the Python. I wish he'd signposted more clearly that these are examples, though, because as it stands it implies this is how to do things, while it really is not. E.g. his "Stuff" example can be reduced to: class Stuff def initialize @a_list = [1, 2, 3, 4] end # The ellipses here are part of the Ruby code for 'forward # all the arguments, including the a block if passed' def each(...) = @a_list.each(...) include Enumerable end Stuff.new.each {|item| puts item } puts Stuff.new.map {|item| item} puts Stuff.new.select{|item| item.even?} One could argue about my use of "..." and endless def, but one certainly would not typically implement each when forwarding to an Array by using a for loop to iterate over it other than to make it relatable to Python developers... And, more controversially perhaps, the last three lines can be reduced to: Stuff.new.each { puts _1 } puts Stuff.new.map.to_a puts Stuff.new.select(&:even?) The first one is one that will cause arguments. The second just showcases that map is pointless here other than as an example - map here effectively just a slow way of duplicating the array, but notably first when forcible evaluated as map without a block will return an Enumerator, and "&:even?" is fairly idiomatic for "call to_proc on this symbol and apply it to the argument", but some might still not be familiar with it.
- re 2y ago> his "Stuff" example can be reduced to [...] The Python example is similarly unidiomatic, reduceable, and flawed for the sake of simplicity (the example doesn't allow multiple independent Stuff iterators), so it's not like Ruby is really at a disadvantage in the article. The point of the example is to illustrate the mechanics of custom iteration (which forwarding to the encapsulated implementation wouldn't accomplish, for either language) while keeping the rest of the Stuff definition as simple as possible. But yes, a brief mention of including Enumerable wouldn't hurt.
- Spivak 2y agoSurprised that the author is shocked about this. This is what collections.abc is for in Python.