简体   繁体   中英

Block Parameter vs. Block Local Parameter in Ruby

I dont understant where the difference between following two code examples is. The first example has one block parameter and one block local parameter. The second one has two block parameter. I understand that both - block and block local parameter - have their own scope. But what is the difference between both?

x = 10
5.times do |y; x|
x = y
puts "x inside the block: #{x}"
end

puts "x outside the block: #{x}" # <-- gives 10

and

x = 10
5.times do |y, x|
x= y
puts "x inside the block: #{x}"
end

puts "x outside the block: #{x}" # <-- gives also 10

Practically it's the same.

Semantically however, your second example is wrong: You pass a second parameter ( x ) to #times which needs only one, so it is totally unecessary . It's just that Ruby by design does not complain when you pass extra parameters to blocks.

You should however use block local parameters when you want to be sure variables used in the block do not accidentally overwrite or reference variables outside the block's scope , eg:

x = 10
5.times do |y|
  x = 20
end
puts x # => 20

x = 10
5.times do |y; x|
  x = 20
end
puts x # => 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM