Some questions on ruby - case2(can carry local variable through scope of block?)

##########################

  1. cat case2.rb
    ##########################
    #!/usr/bin/env ruby

def check_status(servers)
servers.each do |server|
# … Skip some code
# if server status is up
status = ‘up’
end
return status
end

servers = [‘s1’, 's2, ‘s3’]
check_status(servers)

##########################
2. run case2.rb get
##########################
case2.rb:9:in check_status': undefined local variable or methodstatus’ for main:Object (NameError)
from case2.rb:13:in `’

##########################
3. my question:
##########################
Is there way transfer local variable(such as ‘status’) out of the
block(such as servers.each)?
I mean don’t define varialbe ‘status’ outside and before servers.each
block.

If you set “status” outside of the block, it should then use that
variable and give it a new value within the block. There are also
different loop methods with different variable scopes.

def check_status(servers)
status = ‘down’
servers.each do |server|
# Code
status = ‘up’
end
status
end

servers = [‘s1’, ‘s2’, ‘s3’]
check_status(servers)

Joel P. wrote in post #1125476:

If you set “status” outside of the block, it should then use that
variable and give it a new value within the block. There are also
different loop methods with different variable scopes.

def check_status(servers)
status = ‘down’
servers.each do |server|
# Code
status = ‘up’
end
status
end

servers = [‘s1’, ‘s2’, ‘s3’]
check_status(servers)

Hi Joel,

If define ‘status’ before servers.each, then ‘status’ in servers.each is
not local variable of block ‘servers.each’, what I want to ask is: is it
possible to carry the block(such as ‘servers.each’ in case2.rb) local
variable(such as ‘status’ here) out of the block?

As far as I know, it’s only possible if you have a variable already
outside the scope of the block, as demonstrated. Any local variable you
declare inside the block vanishes once you exit the block.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs