0

Why are keys not being output after I add a symbol to an array?

I found this question about how to rename files in paperclip. As far as I understand the answer shows a symbol being added to the array so I have been experimenting in the rails console.

However, I ran into a problem; when I add the :original symbol to the array I can only see the output "original" and not the two keys.

The closest I have come to replicating the output I want is example 3 but that has required creating a separate variable and then going into a loop.

Why aren't the other two keys being output?

-------------Example 1----------------------------------------

Photo.first.attachment.styles.keys+[:original].each do |foo|
  puts foo
end


original
 => [:medium, :thumb, :original] 

-----------Example 2-------------------------------------------

Photo.first.attachment.styles.keys.each do |foo|
  puts foo
end

medium
thumb
=> [:medium, :thumb] 

----------Example 3--------------------------------------------

foo = Photo.first.attachment.styles.keys + [:original]

foo.each do |bar|
  puts bar
end

medium
thumb 
original
=> [:medium, :thumb, :original] 
Community
  • 1
  • 1
Sheldon
  • 9,639
  • 20
  • 59
  • 96

1 Answers1

3

The problem you're seeing is precedence: instead of adding :original to keys and iterating, example 1 iterates, then adds.

Another way to enforce the right order is to use parenthesis:

(Photo.first.attachment.styles.keys + [:original]).each do |foo|
  puts foo
end
Ash Wilson
  • 22,820
  • 3
  • 34
  • 45