GavinBelson
GavinBelson

Reputation: 2784

Ruby Variable Binding Inside Loops

I need to loop through an aliases hash, and transform the header array by assigning it values from the aliases hash in a Ruby class.

I can't seem to transform the header array and then have it available after the loop.

How do I transform the header array so it is available for use after the loop?

 header = ["City", "State"]

 aliases = {"City"=>"Las Vegas", "State"=>"Nevada"}

 aliases.each do |k,v|
   header.each do |s|   
     if s == k then
       s = v            
     end
   end
 end

 puts header

Upvotes: 1

Views: 482

Answers (1)

Ronan Lopes
Ronan Lopes

Reputation: 3398

Try it like this:

header = ["City", "State"]

 aliases = {"City"=>"Las Vegas", "State"=>"Nevada"}

 aliases.each do |k,v|
   header.each do |s|   #doesn't see header variable
     if s == k 
      header[header.index(s)] = v            #doesn't see v variable
     end
   end
 end

 puts header

Don't know if I got it right, think it's what you're looking for. Good luck!

EDIT: I would still simplify it like this:

header = ["City", "State"]

aliases = {"City"=>"Las Vegas", "State"=>"Nevada"}

header.each do |s|
  aliases.select{|k,v| k==s}.each do |k,v|
    header[header.index(s)] = v
  end
end
puts header

Upvotes: 2

Related Questions