ruby - Why is my block only executed once? -


why that:

array = (1..20).to_a array.index.each_slice(5) |slice|   puts slice.inspect end 

returns:

[1, 2, 3, 4, 5] [6, 7, 8, 9, 10] [11, 12, 13, 14, 15] [16, 17, 18, 19, 20] 

while:

other_array = [] array = (1..20).to_a array.index.each_slice(5) |slice|   puts slice.inspect   other_array.push(1) end 

returns only:

[1, 2, 3, 4, 5] 

how other_array.push(1) breaks execution of block? obvious conclusion cannot access variables not in scope of block, why that?

i found solution in array documentation. wondered why used index function array when seems want iterate on array. can use array.each_slice without invoking index. index says following: http://ruby-doc.org/core-2.2.0/array.html#method-i-index

returns index of first object in ary such object == obj.

if block given instead of argument, returns index of first object block returns true. returns nil if no match found

so code evaluates block , checks if result true. in first example puts returns nil. nil false.
second example returns object of array containing single 1.
in ruby every condition true, if not false or nil. can see here:

if nil    puts "foo" end => nil  other_array = [1] if other_array   puts "foo" end => "foo" 

so block in second example returns not-false not run again, because found "valid" result.

for return, maybe should know ruby returns last expression in scope, if no other return given. returns other_array. if don't want reformat code following:

other_array = [] array = (1..20).to_a array.index.each_slice(5) |slice|   puts slice.inspect   other_array.push(1)   nil  end 

this force block return nil , iteration work.


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -