3 ms·
the key difference is that in ruby, `join` is implemented in the `Enumerable` mixin (which provides a whole suite of functionality to any object with an `each`
by zem 6y ago
the key difference is that in ruby, `join` is implemented in the `Enumerable` mixin (which provides a whole suite of functionality to any object with an `each` method). if your own class wants to support `join`, it has to both implement `each` and explicitly mix in `Enumerable`.
in python, `join` is implemented in the `string` class, and the argument is an iterable. therefore, if your class wants to support `join`, it needs to implement the `__iter__` method (python's equivalent of ruby's `each`), but it does not need to also mix in an implementation of `join`.
it's mostly a cultural difference between ruby and python - the ruby ecosystem leans more heavily towards mixins and implementing generic functionality by attaching methods to objects, whereas the python ecosystem leans more heavily towards implementing generic functionality by providing functions (or methods on an external class) that accept generic objects.
- pmontra 6y agoActually join is a method of Array https://ruby-doc.org/core-2.6.5/Array.html https://ruby-doc.org/core-2.6.5/Array.html A class that wants to support join has to implement to_s. The definition of join is > join(separator=$,) → str > Returns a string created by converting each element of the array to a string, separated by the given separator. If the separator is nil, it uses current $,. If both the separator and $, are nil, it uses an empty string. If the class doesn't implement to_s Object.to_s kicks in and displays something like "#<SomeClass:0x000055a321fa2bb0>" Enumerable is really a mixin https://ruby-doc.org/core-2.6.5/Enumerable.html https://ruby-doc.org/core-2.6.5/Enumerable.html but join is not listed in its methods. There is another reply of mine with an example of a class can be used in join and doesn't mix in Enumerable.
- zem 6y agooops, right you are, it's not defined on Enumerable (though i do wonder why! `each` does define an iteration order after all)