1

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
3
  • 2
    This code runs fine. "sees" everything it should see (but you assert that it doesn't). Commented Feb 1, 2018 at 15:52
  • You're correct, I think the issue may be that s=v does not change the header. Commented Feb 1, 2018 at 16:07
  • In future, don't be in such a rush to select an answer! Quick selections may discourage other answers, and by waiting awhile (at least a couple of hours, say) readers may point out weaknesses in answers that you may not have thought of. Note that you can always change your selection. Incidentally, I see no reason for the Rails tag. Commented Feb 1, 2018 at 20:35

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

14 Comments

Thanks, that works. It looks like header was getting looped over but the values did not change with my code. Indexing it solves the issue
you call that a simplification? :) header.map! {|s| aliases[s] }
header = aliases.values_at(*header)
OP would do well to learn to avoid mutating stuff like this. Suddenly header is not a header (does not contain header-y values). Makes code impossible to read.
@RonanLopes: I wasn't. That snippet is objectively more complex than the one before. If you don't mind, what exactly is simpler about it? :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.