How can I make method each in Python like its in Ruby? Is that possible, am really do!
In Ruby its looks like:
%w[1 2 3 4].each { |i| puts i}
In Python we have for:
for i in [1, 2, 3]: print(i)
So, I want to make each method in Python, here is my code:
class Iter:
def each(self, data):
processed = data.__iter__()
yield processed.__next__()
if __name__ == "__main__":
test = Iter()
print(list(test.each([1, 2, 3])))
Its working not as each, its return only first element.
Thx in advance!
yield processed.__next__()which only returns the first element of the iterator. Just return the iterator directly fromeach.listand most other constructs can use iterators since iterators are iterables like lists.iterandnextinstead of.__iter__and.__next__directly. In the end, this really just means that youreachis an alias for__iter__. I would just properly implement the iterator interface instead of using Ruby conventions. The two don't appear to be equivalent anyway since Ruby's version takes a function/block/whatever they're called.each) that takes a block (which may be several lines long), and it looks very natural to call. Python's equivalent to Ruby's block is thelambdakeyword, an anaemic one-line-only anonymous function. You can writeeachin Python (in fact, I have done so). But it's just not as useful in a language where blocks are limited to one line.