I'm trying to come up with an elegant way of creating a list from a function that yields values in both Python and Ruby.
In Python:
def foo(x):
for i in range(x):
if bar(i): yield i
result = list(foo(100))
In Ruby:
def foo(x)
x.times {|i| yield i if bar(i)}
end
result = []
foo(100) {|x| result << x}
Although I love working in both languages, I've always been a bit bothered by the Ruby version having to initialize the list and then fill it. Python's yield
results in simple iteration, which is great. Ruby's yield
invokes a block, which is also great, but when I just want to fill a list, it feels kinda clunky.
Is there a more elegant Ruby way?
UPDATE Reworked the example to show that the number of values yielded from the function isn't necessarily equal to x.