I am trying to create an elegant way to create a list from a function that gives 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}
Despite the fact that I like working in both languages, I was always a little worried about the version of Ruby that was supposed to initialize the list and then fill it. Python yieldleads to a simple iteration, which is great. Ruby yieldcalls the block, which is also great, but when I just want to populate the list, it looks a little awkward.
Is there a more elegant Ruby way?
UPDATE Reworked the example to show that the number of values received from the function is not necessarily x.