HI ,
i am using a COnstant hash in my model User as
MYUSER = { :firstname => "First Name", :开发者_运维百科lastname => "LAst Name", :designation => "My Designation" }
Now in my views , i have a loop where i have all those field names (firstname,lastname,designation)
So i try to send this field name as a key in
<% @userfields.sort.each do |userfield| %>
<tr>
<td>
<% @userkey=userfield%>
<%= @userkey%> # gives the exact field names
<%= User::MYUSER[:@userkey]%> # this doesnt gives anything
<td></tr>
<%end%>
How to rectify this ?? give some suggestions
When you use a variable as index to a hash, you should not specify the colon, the correct syntax would be:
User::MYUSER[@userkey]
or
User::MYUSER[@userkey.to_sym]
depending on the value in @userkey.
However, you could also loop the MYUSER constant directly like this:
<% User::MYUSER.keys.each do |key| %>
<tr>
<td>Key: <%= key %></td>
<td>Value: <%= User::MYUSER[key] %></td>
</tr>
<% end %>
I agree with @DanneManne's answer. But more specifically, you can iterate through records using each_pair:
<% User::MYUSER.each_pair do |key, value| %>
<tr>
<td>Key: <%= key %></td>
<td>Value: <%= value %></td>
</tr>
<% end %>
精彩评论