3

I'm new to Ruby, and I'm trying the following:

mySet = numOfCuts.times.map{ rand(seqLength) }

but I get the 'yield called out of block' error. I'm not sure what his means. BTW, this question is part of a more general question I asked here.

Community
  • 1
  • 1
Esteban Araya
  • 29,284
  • 24
  • 107
  • 141

5 Answers5

9

The problem is that the times method expects to get a block that it will yield control to. However you haven't passed a block to it. There are two ways to solve this. The first is to not use times:

mySet = (1..numOfCuts).map{ rand(seqLength) }

or else pass a block to it:

mySet = []
numOfCuts.times {mySet.push( rand(seqLength) )}
user11318
  • 9,273
  • 2
  • 25
  • 25
1

if "numOfCuts" is an integer,

5.times.foo   

is invalid

"times" expects a block.

5.times{   code here   } 
Kent Fredric
  • 56,416
  • 14
  • 107
  • 150
1

You're combining functions that don't seem to make sense -- if numOfCuts is an integer, then just using times and a block will run the block that many times (though it only returns the original integer:

irb(main):089:0> 2.times {|x| puts x}
0
1
2

map is a function that works on ranges and arrays and returns an array:

irb(main):092:0> (1..3).map { |x| puts x; x+1 }
1
2
3
[2, 3, 4]

I'm not sure what you're trying to achieve with the code - what are you trying to do? (as opposed to asking specifically about what appears to be invalid syntax)

Kyle Burton
  • 26,788
  • 9
  • 50
  • 60
1

Bingo, I just found out what this is. Its a JRuby bug.

Under MRI

>> 3.times.map
=> [0, 1, 2]
>> 

Under JRuby

irb(main):001:0> 3.times.map
LocalJumpError: yield called out of block
    from (irb):2:in `times'
    from (irb):2:in `signal_status'
irb(main):002:0> 

Now, I don't know if MRI (the standard Ruby implementation) is doing the right thing here. It probably should complain that this does not make sense, but when n.times is called in MRI it returns an Enumerator, whereas Jruby complains that it needs a block.

Sam Saffron
  • 128,308
  • 78
  • 326
  • 506
0

Integer.times expects a block. The error message means the yield statement inside the times method can not be called because you did not give it a block.

As for your code, I think what you are looking for is a range:

(1..5).map{ do something }

Here is thy rubydoc for the Integer.times and Range.

horseyguy
  • 29,455
  • 20
  • 103
  • 145
jop
  • 82,837
  • 10
  • 55
  • 52