What does block exiting mean in Ruby?

I am new to Ruby and I am trying the following:

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

but I get the error "yield called out of block". I do not know what his means are. By the way, this question is part of a more general question that I asked here .

+3
source share
5 answers

The problem is that the times method expects to get a block that it will control. However, you did not give him the block. This can be solved in two ways. First, do not use time:

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

or pass it a block:

mySet = []
numOfCuts.times {mySet.push( rand(seqLength) )}
+9
source

if "numOfCuts" is an integer,

5.times.foo   

wrong

"times" is waiting for a block.

5.times{   code here   } 
+1
source

, , , - numOfCuts , , ( :

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

map - , :

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

, - ? ( , )

+1

, , . JRuby.

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

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> 

, , MRI ( Ruby) . , , , ntht MRI, Enumerator, Jruby , .

+1

Integer.times . , yield times , .

, , :

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

Here is your rubydoc for Integer.times and Range .

0
source

Source: https://habr.com/ru/post/1697363/


All Articles