Alon Shmiel
Alon Shmiel

Reputation: 7121

get element of hash table

I run:

params[:taxes].each { |pst|
   puts(pst)
}

and got:

{"country"=>"USA", "tax"=>"20"}

how can I got the parameter of the country?

I tried:

pst[:country]
pst["country"]

but it doesn't print anything.

any help appreciated!

Upvotes: 1

Views: 357

Answers (3)

Konrad Reiche
Konrad Reiche

Reputation: 29553

Since you are iterating a hash with defining only one element (here pst) it returns an array with length two in every step. You would receive "USA" only in the first iteration by calling pst[1][:country]. Maybe it is more convenient for you to iterate with defining two elements in the block, enabling you to access the key and value in every step:

params[:taxes].each do |key, value|
   puts value[:country]
end

Upvotes: 5

shweta
shweta

Reputation: 8169

Try:

params[:taxes].each_pair do |key, value|
  puts value[:country]
end

to get country name

Upvotes: 1

Alexander
Alexander

Reputation: 3245

Try with single quotes

pst['country']

Upvotes: 1

Related Questions