Flip
Flip

Reputation: 6771

How can I iterate over part of a hash in Ruby

In a Rails environment i get a params hash from a form. Besides others, like

params[:vocab][:name] 
params[:vocab][:priority]

I have the 3 fields tag_1, tag_2, tag_3 whose values are stored in

params[:vocab][:tag_1] 
params[:vocab][:tag_2] 
params[:vocab][:tag_3]

My question is: Can I iterate over these three hash keys? I want to do sth like

for i in 1..3 do
  iterator = ":tag_" + i.to_s
  puts params[:vocab][iterator.to_sym]
end

but that doesn't work.

Upvotes: 0

Views: 92

Answers (2)

Chris Heald
Chris Heald

Reputation: 62668

You can construct symbols via interpolation; prefixing a string with a colon will cause Ruby to interpret it as a symbol.

(1..3).each do |i|
  puts params[:vocab][:"tag_#{i}"]
end

Upvotes: 3

Marek Lipka
Marek Lipka

Reputation: 51171

Your approach doesn't work because:

':tag_2'.to_sym
# => :":tag_2"

so it would work if you remove leading colon from ":tag_" + i.to_s

You can also do it this way, iterating over keys:

[:tag_1, :tag_2, :tag_3].each { |key| puts params[:vocab][key] }

Upvotes: 3

Related Questions