3

Lets say have method:

def in_block
  x = "This variables outer block"
  3.times do |i|
    x = i
    puts "x inside block - #{x}"
  end
  puts x
end
in_block

# >> x inside block - 0
# >> x inside block - 1
# >> x inside block - 2
# >> 2

How i can protect my x variables?

Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103

1 Answers1

5

Separate parameter in block by semicolon ; this indicates that the block need its own x, unrelated to any x that have been created already in outside the block.

def in_block
  x = "This variables outer block"
  3.times do |i; x|
    x = i
    puts "x inside block - #{x}"
  end
  puts x
end
in_block

# >> x inside block - 0
# >> x inside block - 1
# >> x inside block - 2
# >> This variables outer block

But how about simple ,? it is not the same. Look example that block takes two parameters:

def in_block
  #x = "This variables outer block"
  [1,2,3,4].each_with_index do |i; x|
  puts x.class
    x = i
    puts "x inside block - #{x}"
  end
  #puts x
end

in_block # => [1, 2, 3, 4]

# >> NilClass
# >> x inside block - 1
# >> NilClass
# >> x inside block - 2
# >> NilClass
# >> x inside block - 3
# >> NilClass
# >> x inside block - 4

and with ,:

def in_block
  #x = "This variables outer block"
  [1,2,3,4].each_with_index do |i, x|
  puts x.class
    x = i
    puts "x inside block - #{x}"
  end
  #puts x
end

in_block # => [1, 2, 3, 4]

# >> Fixnum
# >> x inside block - 1
# >> Fixnum
# >> x inside block - 2
# >> Fixnum
# >> x inside block - 3
# >> Fixnum
# >> x inside block - 4
Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103