Forum: Ruby some questions on ruby - case2(can carry local variable through scope of block?)

7b3d60a2de005a458e45f2722345f3c6?d=identicon&s=25 Previn Lin (previn)
on 2013-10-24 10:51
##########################
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 method
`status' for main:Object (NameError)
        from case2.rb:13:in `<main>'

##########################
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.
14b5582046b4e7b24ab69b7886a35868?d=identicon&s=25 Joel Pearson (virtuoso)
on 2013-10-24 11:16
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)
7b3d60a2de005a458e45f2722345f3c6?d=identicon&s=25 Previn Lin (previn)
on 2013-10-24 11:35
Joel Pearson 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?
14b5582046b4e7b24ab69b7886a35868?d=identicon&s=25 Joel Pearson (virtuoso)
on 2013-10-24 11:53
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.
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.