2

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!

4
  • 1
    It only returns one element because you did yield processed.__next__() which only returns the first element of the iterator. Just return the iterator directly from each. list and most other constructs can use iterators since iterators are iterables like lists. Commented Dec 25, 2022 at 15:05
  • 1
    Also, you should really use iter and next instead of .__iter__ and .__next__ directly. In the end, this really just means that your each is 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. Commented Dec 25, 2022 at 15:08
  • @Carcigenicate, hmm, ok thats nice info, thx u friend Commented Dec 25, 2022 at 15:22
  • 1
    The reason you don't see this is a difference in philosophy. Ruby is an expression oriented language, so you can write a function (like 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 the lambda keyword, an anaemic one-line-only anonymous function. You can write each in Python (in fact, I have done so). But it's just not as useful in a language where blocks are limited to one line. Commented Dec 25, 2022 at 20:44

1 Answer 1

1
class Iter:
    def each(self, data):
        yield from data

if __name__ == "__main__":
    test = Iter()
    for i in test.each([1, 2, 3]):
        print(i)

To implement the each method in python that is similar to Ruby, you can use the yield statement. If you use it inside a for it should work that way.

I'll also add the link to the documentation of yield statement here.

Sign up to request clarification or add additional context in comments.

2 Comments

Thx for your answer! But, can I do it without for ?
@SonyMag They're using for to replace the list call you were using. They have roughly the same purpose: to pull elements from the iterator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.