views:

175

answers:

4

Given this hash that comes though :params

"positions"=>{
    "1"=>{"x"=>"50", "y"=>"30"}, 
    "2"=>{"x"=>"22", "y"=>"53"}, 
    "3"=>{"x"=>"68", "y"=>"35"}
 }

How would I do this? (doesn't work, but attempting to show what I want to do)

params[:positions].each do |position|
  logger.info(position.x)
end

I know, painfully beginner stuff ...

I get a NoMethodError (undefined method 'x' for ["1", {"x"=>"50", "y"=>"30"}]:Array)

+1  A: 

I think you're looking for position[x] instead of position.x.

Jon Konrath
Tried that earlier too, "Undefined local variable or method 'x' for #<controller>"
rpflo
Actually, position['x'] is what you're looking for in this case.
Jakob S
+2  A: 

You could do something like this:

positions = {
  "1"=>{"x"=>"50", "y"=>"30"},
  "2"=>{"x"=>"22", "y"=>"53"},
  "3"=>{"x"=>"68", "y"=>"35"}
}

positions.each_value do |hash|
  logger.info(hash['x'])
end

The each_value method will pull out the hashes (e.g. {"x"=>"50", "y"=>"30"}). In these hashes, your keys are strings, so you need to look inside these hashes with stringed keys.

theIV
+11  A: 

I think what you want is

params[:positions].each do |index, coords|
  logger.info(coords['x'])
end

If you don't care about the indexes, you could also just use params[:positions].values.each do |coords| instead.

John Hyland
This is the answer you're looking for.
Josh Matthews
A: 

If you use Enumerable#each with a Hash you need to capture two block variables (this "unwraps" the array of key/value into two distinct variables). Also, Ruby does not use dot-syntax for hashes (this is not Javascript).

 some_hash.each do | (key, value)
    puts value["x"]
 end

This saves you from assembling an array of values first (using Hash#values).

Julik