Home>
array_hash = [[home>= tokyo], [home>= Kyoto]]
array_hash.each do | var |
a = var [home]
end


I learned that a variable in a block has a lifetime only in the block.
If there is something like a hash in this array, is there no way to reference the variable "a" in the block outside the block?
I saw a description that can be referenced outside the block using Proc and lamda, but I do not know whether it applies to each method etc. with such an array as a receiver,< br />

  • Answer # 1

    No.

    Define variables in advance

    array_hash = [{home: "tokyo"}, {home: "Kyoto"}]
    a = nil
    array_hash.each do | var |
      a = var [: home]
    end
    p a # =>"Kyoto"

    Use Enumerable # inject

    array_hash = [{home: "tokyo"}, {home: "Kyoto"}]
    a = array_hash.inject (nil) do | _, var |
      var [: home]
    end
    p a # =>"Kyoto"

    If you want to do something about the last element, uselast,[-1], etc.

    array_hash = [{home: "tokyo"}, {home: "Kyoto"}]
    a = array_hash.last [: home]
    p a # =>"Kyoto"

    I think these methods are fine in most cases

  • Answer # 2

    If you want to refer to it outside the block, you just need to define it outside the block