Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby protect outer variable inside block [duplicate]

Tags:

ruby

block

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?

like image 412
Philidor Avatar asked Jul 31 '26 05:07

Philidor


1 Answers

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
like image 80
Philidor Avatar answered Aug 02 '26 19:08

Philidor