Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Ruby method yield as an iterator or return an array depending on context?

I have an arbitrary method in Ruby that yields multiple values so it can be handed to a block:

def arbitrary
  yield 1
  yield 2
  yield 3
  yield 4
end

arbitrary { |x| puts x }

I'd like to modify this method so that, if there is no block, it just returns the values as an array. So this construct would work as well:

myarray = arbitrary
p a -----> [1, 2, 3, 4, 5]

Is this possible in Ruby?

like image 853
sh-beta Avatar asked Jun 26 '09 18:06

sh-beta


2 Answers

def arbitrary
  values = [1,2,3,4]
  return values unless block_given? 
  values.each { |val| yield(val) }
end
arbitrary { |x| puts x }
arbitrary
like image 53
Subba Rao Avatar answered Oct 05 '22 01:10

Subba Rao


There is a syntax for that:

def arbitrary(&block)
  values = [1, 2, 3, 4]
  if block
    values.each do |v|
      yield v
    end
  else
    values
  end
end

Note:

yield v

Can be replaced with:

block.call v
like image 38
bltxd Avatar answered Oct 05 '22 01:10

bltxd