views:

104

answers:

4

Hello I have following problem.

I have a hash filled with the html parameters (params):

Parameters:  "info"=>{"parameter2"=>{"r1"=>"aa", "r2"=>"bb", "r3"=>"cc", "r4"=>"dd", "r5"=>"ee"}

You can access this values like this:

<%= params[:info][:parameter2][:r1] %> --> it works fine

But I have a loop, and want to access these values through a variable like that:

<% for number_row in (1..@numb_rows) %>

<%= params[:info][:parameter2]["r" + number_row.to_s]  %>

<% end %>

--> it doesn´t work . I always get this error :

can't convert nil into String

But the "r1" does exist. Why it always says, that it can not convert nil into String.

How I can access these params with an changing variable ??

I need something like this : params[:info][:parameter2][@var]

+2  A: 

Sounds very un-ruby. Try

params[:info][:parameter2].each do |key, value|

...

Tass
the problem is, that in need this in another loop, and I only need one value from this hash
wabbiti
`value` is the current value of the iteration. What do you exactly want to do?
Tass
Yes the value is the current value of the iteration. I want to fetch the key-value from that hash. The problem is somehow that what Nate Pinchot explained (see next answer).
wabbiti
Why do you want external iteration? Most often, Ruby provides better means.
Tass
because I have an different iteration, where I only want to look up the params from that parameter2 .
wabbiti
A: 

In Ruby, things with a colon in front of it are a Symbol. The error you are getting is correct, since you are referencing "r1", instead of :r1.

You need to use to_sym to make a Symbol from a String.

n = "r" + number_row.to_s
params[:info][:parameter2][n.to_sym]
Nate Pinchot
I was looking for something like this. Thx. But unfortunately I get the same error: can't convert nil into String Somehow it do not accepts vars: n = "r" + "1" --> it works, it can transform it into a symbol n = "r" + number_row.to_s --> than he can not transform it into a Symbol
wabbiti
Sorry, I forgot `.to_s` on `number_row`. Here's a test in irb http://i.imgur.com/JYMTV.png
Nate Pinchot
A: 

Try this way !

<% params[:info][:parameter2].keys do |key| %>

<%= params[:info][:parameter2][key] %>

<% end %>
krunal shah
A: 

This works for me:

1.upto(@numb_rows).each do |i|
  puts params['info']['parameter2']["r#{i}"]}
end
Dave Sims
Yes, this works ,if you change that into this:1.upto(@numb_rows-1) { |i| puts params[:info][:parameter2]["r#{i.to_s}"]}Thx a lot.
wabbiti
Glad that helped. And btw, Ruby will implicitly convert the integer to a string. You don't have to call to_s. And do you really want to offset @numb_rows by -1? That will leave out the last row (r5), right?
Dave Sims
I had there somewhere an error, because the range was somehow too big. Than I was testing, if it is work if the @numb_rows max number is minus one. Then it worked fine.But the main thing is, that your codes works for me :) . Thanks a lot !!
wabbiti