Can a Ruby method yield as an iterator or return an array depending on context? -
In Ruby I have an arbitrary method that generates many values, so that it can be handed over to any block: < / P>
DEF arbitrary yield 1 yield 2 yield 3 yield 4 end arbitrary {| X | Say x}
I would like to modify this method so that if there is no block, it only gives value as an array. This build will also work:
myarray = arbitrary p a -----> [1, 2, 3, 4, 5]
Is this possible in Ruby?
There is a syntax for this:
def arbitrary (& amp; ; Block) value = [1, 2, 3, 4] If the block value | Yield vs end and val and end
Note:
can be replaced with yield v
: < / P>
block.call v
Comments
Post a Comment