简体   繁体   中英

accessing variables outside block

I have this code:

grades = ["Slect", "Choice", "Prime"]
names = grades.map{ |j| j.downcase }
names.zip(grades) do |r,n|
    r = Steak.new
    r.grade = n
    r
end

ObjectSpace.each_object(Steak) {|x| p x}

shows that Steak has 3 instances and grades get correct values assigned.

But I can't access choice for example outside the block.

any solutions?

Normally you approach this by doing a series of transforms that build up data. Your alterations to r are ignored, that's just reassigning a local variable that's later discarded since you don't actually attach it to anything.

The better way is to return this as a Hash with the right key:

class Steak
  attr_accessor :grade
end

grades = [ "Select", "Choice", "Prime" ]

map = Hash[
  grades.map do |grade|
    steak = Steak.new
    steak.grade = grade.downcase

    [ grade, steak ]
  end
]

# => {"Select"=>#<Steak:0x007fc6ef01bd60 @grade="select">, "Choice"=>#<Steak:0x007fc6ef01bcc0 @grade="choice">, "Prime"=>#<Steak:0x007fc6ef01bc20 @grade="prime">}

The only way to "access variables outside a block" is to make sure the block returns the data, or to have the variables defined prior to the block so they're part of the closure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM